登录传入医院id

字典模块
医院省份统计
设置当前医院
mysql版本远程
This commit is contained in:
yy 2024-05-29 09:33:22 +08:00
parent 07ec8d5b3b
commit ada27c3185
48 changed files with 1904 additions and 372 deletions

View File

@ -4,17 +4,14 @@ import cn.hutool.core.codec.Base64;
import cn.hutool.extra.spring.SpringUtil;
import com.rax.admin.api.entity.SysOauthClientDetails;
import com.rax.admin.api.feign.RemoteClientDetailsService;
import com.rax.admin.api.feign.RemoteUserService;
import com.rax.common.core.constant.SecurityConstants;
import com.rax.common.core.util.R;
import com.rax.common.core.util.RedisUtils;
import com.rax.common.core.util.SpringContextHolder;
import com.rax.common.security.service.RaxUser;
import com.rax.common.security.util.OAuth2ErrorCodesExpand;
import com.rax.common.security.util.ScopeException;
import jakarta.annotation.Resource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.*;

View File

@ -28,6 +28,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.www.BasicAuthenticationConverter;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
@ -105,6 +106,11 @@ public class RaxDaoAuthenticationProvider extends AbstractUserDetailsAuthenticat
String grantType = WebUtils.getRequest().get().getParameter(OAuth2ParameterNames.GRANT_TYPE);
String clientId = WebUtils.getRequest().get().getParameter(OAuth2ParameterNames.CLIENT_ID);
Long hospitalId = Long.valueOf(WebUtils.getRequest().get().getParameter("hospitalId"));
if (hospitalId == null) {
throw new InternalAuthenticationServiceException("hospitalId is empty");
}
if (StrUtil.isBlank(clientId)) {
clientId = basicConvert.convert(request).getName();
@ -124,7 +130,7 @@ public class RaxDaoAuthenticationProvider extends AbstractUserDetailsAuthenticat
}
try {
UserDetails loadedUser = optional.get().loadUserByUsername(username);
UserDetails loadedUser = optional.get().loadUserByUsername(username, hospitalId);
if (loadedUser == null) {
throw new InternalAuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");

View File

@ -1,6 +1,7 @@
package com.rax.auth.support.password;
import com.rax.admin.api.feign.RemoteClientDetailsService;
import com.rax.admin.api.feign.RemoteUserService;
import com.rax.auth.support.base.OAuth2ResourceOwnerBaseAuthenticationProvider;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

View File

@ -48,4 +48,9 @@ public interface CacheConstants {
*/
String PARAMS_DETAILS = "params_details";
/**
* 当前医院id
*/
String CURRENT_HOSPITAL = "hospital:current_hospital";
}

View File

@ -86,4 +86,9 @@ public class RaxAppUserDetailsServiceImpl implements RaxUserDetailsService {
return SecurityConstants.MOBILE.equals(grantType);
}
@Override
public UserDetails loadUserByUsername(String phone, Long hospitalId) {
return null;
}
}

View File

@ -65,14 +65,18 @@ public class RaxUser extends User implements OAuth2AuthenticatedPrincipal {
@Getter
private final String phone;
@Getter
private final String chineseName;
public RaxUser(Long id, Long deptId, Long hospitalId, String username, String password, String phone, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked,
boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, String chineseName,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.id = id;
this.deptId = deptId;
this.hospitalId = hospitalId;
this.phone = phone;
this.chineseName = chineseName;
}
/**

View File

@ -68,16 +68,18 @@ public interface RaxUserDetailsService extends UserDetailsService, Ordered {
// 构造security用户
return new RaxUser(user.getUserId(), user.getDeptId(), user.getHospitalId(), user.getUsername(),
SecurityConstants.BCRYPT + user.getPassword(), user.getPhone(), true, true, true,
StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL), authorities);
StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL), user.getName(), authorities);
}
UserDetails loadUserByUsername(String username, Long hospitalId);
/**
* 通过用户实体查询
* @param raxUser user
* @return
*/
default UserDetails loadUserByUser(RaxUser raxUser) {
return this.loadUserByUsername(raxUser.getUsername());
return this.loadUserByUsername(raxUser.getUsername(), raxUser.getHospitalId());
}
}

View File

@ -29,6 +29,7 @@ import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/**
* 用户详细信息
@ -51,7 +52,7 @@ public class RaxUserDetailsServiceImpl implements RaxUserDetailsService {
*/
@Override
@SneakyThrows
public UserDetails loadUserByUsername(String username) {
public UserDetails loadUserByUsername(String username, Long hospitalId) {
Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
if (cache != null && cache.get(username) != null) {
return (RaxUser) cache.get(username).get();
@ -59,6 +60,7 @@ public class RaxUserDetailsServiceImpl implements RaxUserDetailsService {
UserDTO userDTO = new UserDTO();
userDTO.setUsername(username);
userDTO.setHospitalId(hospitalId);
R<UserInfo> result = remoteUserService.info(userDTO, SecurityConstants.FROM_IN);
UserDetails userDetails = getUserDetails(result);
if (cache != null) {
@ -72,4 +74,8 @@ public class RaxUserDetailsServiceImpl implements RaxUserDetailsService {
return Integer.MIN_VALUE;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return null;
}
}

View File

@ -1300,4 +1300,13 @@ CREATE TABLE `sys_hospital_manager` (
`user_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
drop table if exists sys_hospital_current;
create table sys_hospital_current
(
user_id varchar(36) not null,
hospital_id varchar(36) not null,
constraint sys_hospital_current_pk
unique (user_id)
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;

View File

@ -200,6 +200,7 @@ public class SysDictController {
*/
@SysLog("新增字典项")
@PostMapping("/item")
@PreAuthorize("@pms.hasPermission('sys_dict_add')")
@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
public R save(@RequestBody SysDictItem sysDictItem) {
return R.ok(sysDictItemService.save(sysDictItem));
@ -213,6 +214,7 @@ public class SysDictController {
*/
@SysLog("修改字典项")
@PutMapping("/item")
@PreAuthorize("@pms.hasPermission('sys_dict_edit')")
public R updateById(@RequestBody SysDictItem sysDictItem) {
return sysDictItemService.updateDictItem(sysDictItem);
}
@ -225,6 +227,7 @@ public class SysDictController {
*/
@SysLog("删除字典项")
@DeleteMapping("/item/{id}")
@PreAuthorize("@pms.hasPermission('sys_dict_del')")
public R removeDictItemById(@PathVariable Long id) {
return sysDictItemService.removeDictItem(id);
}

View File

@ -5,13 +5,16 @@ import com.rax.admin.api.entity.SysHospital;
import com.rax.admin.service.SysHospitalService;
import com.rax.common.core.util.R;
import com.rax.common.log.annotation.SysLog;
import com.rax.common.security.service.RaxUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@ -35,6 +38,7 @@ public class SysHospitalController {
@SysLog(value = "医院信息删除")
@PostMapping("/deleteHospitalByIds")
@PreAuthorize("@pms.hasPermission('sys_hospital_del')")
@Operation(description = "根据id删除医院信息", summary = "根据id删除医院信息")
R<Boolean> deleteHospitalById(String[] ids) {
return sysHospitalService.deleteHospitalByIds(ids);
@ -42,6 +46,7 @@ public class SysHospitalController {
@SysLog(value = "医院信息修改")
@PostMapping("/updateHospital")
@PreAuthorize("@pms.hasPermission('sys_hospital_edit')")
@Operation(description = "医院信息修改", summary = "医院信息修改")
R<Boolean> updateHospital(HospitalDTO hospitalDTO) {
return sysHospitalService.updateHospital(hospitalDTO);
@ -49,6 +54,7 @@ public class SysHospitalController {
@SysLog(value = "新建医院信息")
@PostMapping("/saveHospital")
@PreAuthorize("@pms.hasPermission('sys_hospital_add')")
@Operation(description = "新建医院信息", summary = "新建医院信息")
R<Boolean> saveHospital(HospitalDTO hospitalDTO) {
return sysHospitalService.saveHospital(hospitalDTO);
@ -76,7 +82,7 @@ public class SysHospitalController {
@SysLog(value = "添加医院管理员")
@PostMapping("/saveHospitalManager")
@Operation(description = "添加医院管理员", summary = "添加医院管理员")
@PreAuthorize("@pms.hasPermission('sys_user_del')")
@PreAuthorize("@pms.hasPermission('sys_hospital_manager_add')")
R saveHospitalManager(String userId, String hospitalId) {
boolean status = sysHospitalService.saveHospitalManager(userId, hospitalId);
return R.ok(status);
@ -88,4 +94,29 @@ public class SysHospitalController {
List list = sysHospitalService.getHospitalManager(hospitalId);
return R.ok(list);
}
@PostMapping("/changeHospital")
@PreAuthorize("@pms.hasPermission('sys_hospital_change')")
@SysLog(value = "切换医院")
R changeHospital(String id) {
RaxUser raxUser = (RaxUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String userId = String.valueOf(raxUser.getId());
return R.ok(sysHospitalService.changeHospital(id, userId));
}
@PostMapping("/getCurrentHospital")
R getCurrentHospital() {
return R.ok(sysHospitalService.getCurrentHospital());
}
@PostMapping("/getCountByProvince")
R getCountByProvince() {
return R.ok(sysHospitalService.getCountByProvince());
}
@PostMapping("/getCountByCity")
R getCountByCity(String province) {
return R.ok(sysHospitalService.getCountByCity(province));
}
}

View File

@ -1,13 +1,16 @@
package com.rax.admin.controller;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rax.admin.api.entity.SysMessage;
import com.rax.admin.api.vo.SysMessageVO;
import com.rax.admin.service.SysHospitalService;
import com.rax.admin.service.SysMessageService;
import com.rax.common.core.util.R;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@ -21,29 +24,39 @@ public class SysMessageController {
@Autowired
private SysMessageService sysMessageService;
@Autowired
private SysHospitalService sysHospitalService;
@PostMapping("/save")
@PreAuthorize("@pms.hasPermission('sys_msg_add')")
public R save(SysMessageVO sysMessageVO) {
return sysMessageService.saveMessage(sysMessageVO);
}
@PostMapping("/update")
@PreAuthorize("@pms.hasPermission('sys_msg_edit')")
public R update(SysMessageVO sysMessageVO) {
return sysMessageService.updateMessage(sysMessageVO);
}
@PostMapping("/page")
public R page(Page page, SysMessageVO sysMessageVO) {
String hospitalId = sysHospitalService.getCurrentHospital();
return R.ok(sysMessageService.page(page, Wrappers.<SysMessage>lambdaQuery()
.eq(StringUtils.hasText(sysMessageVO.getCategory()),
SysMessage::getCategory,
sysMessageVO.getCategory())
.eq(SysMessage::getDelFlag, 0)
.eq(SysMessage::getHospital, hospitalId)
.like(StringUtils.hasText(sysMessageVO.getMessage()),
SysMessage::getMessage,
sysMessageVO.getMessage())));
sysMessageVO.getMessage()))
.addOrder(OrderItem.desc("create_time"))
);
}
@PostMapping("/delete")
@PreAuthorize("@pms.hasPermission('sys_msg_del')")
public R delete(String ids) {
return sysMessageService.deleteMessage(ids);
}

View File

@ -104,7 +104,7 @@ public class SysRoleController {
*/
@GetMapping("/list")
public R listRoles() {
return R.ok(sysRoleService.list(Wrappers.emptyWrapper()));
return R.ok(sysRoleService.list(Wrappers.<SysRole>lambdaQuery().ne(SysRole::getRoleCode, "ROLE_ADMIN")));
}
/**

View File

@ -4,8 +4,11 @@ import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rax.admin.api.dto.UserDTO;
import com.rax.admin.api.entity.SysRole;
import com.rax.admin.api.entity.SysUser;
import com.rax.admin.api.vo.UserExcelVO;
import com.rax.admin.service.SysHospitalService;
import com.rax.admin.service.SysRoleService;
import com.rax.admin.service.SysUserService;
import com.rax.common.core.constant.CommonConstants;
import com.rax.common.core.exception.ErrorCodes;
@ -13,6 +16,7 @@ import com.rax.common.core.util.MsgUtils;
import com.rax.common.core.util.R;
import com.rax.common.log.annotation.SysLog;
import com.rax.common.security.annotation.Inner;
import com.rax.common.security.service.RaxUser;
import com.rax.common.security.util.SecurityUtils;
import com.rax.excel.annotation.RequestExcel;
import com.rax.excel.annotation.ResponseExcel;
@ -24,6 +28,8 @@ import lombok.AllArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@ -42,28 +48,59 @@ public class SysUserController {
private final SysUserService userService;
private final SysRoleService roleService;
private final static String ADMIN_ROLE_CODE = "ROLE_ADMIN";
private final SysHospitalService sysHospitalService;
/**
* 获取指定用户全部信息
*
* @return 用户信息
*/
@Inner
@GetMapping(value = { "/info/query" })
public R info(@RequestParam(required = false) String username, @RequestParam(required = false) String phone) {
@GetMapping(value = {"/info/query"})
public R info(@RequestParam(required = false) String username, @RequestParam(required = false) String phone, @RequestParam(required = false) String hospitalId) {
SysUser user = userService.getOne(Wrappers.<SysUser>query()
.lambda()
.eq(StrUtil.isNotBlank(username), SysUser::getUsername, username)
.eq(StrUtil.isNotBlank(phone), SysUser::getPhone, phone));
.lambda()
.eq(StrUtil.isNotBlank(username), SysUser::getUsername, username)
.eq(StrUtil.isNotBlank(phone), SysUser::getPhone, phone)
.eq(StringUtils.hasText(hospitalId), SysUser::getHospitalId, hospitalId));
SysUser user1 = userService.getOne(Wrappers.<SysUser>query()
.lambda()
.eq(StrUtil.isNotBlank(username), SysUser::getUsername, username)
.eq(StrUtil.isNotBlank(phone), SysUser::getPhone, phone));
if (user == null) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username));
if (user1 == null) {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username));
} else {
List<SysRole> rolesByUserId = roleService.findRolesByUserId(user1.getUserId());
boolean isAdmin = false;
for (SysRole role: rolesByUserId) {
if (ADMIN_ROLE_CODE.equals(role.getRoleCode())) {
isAdmin = true;
break;
}
}
if (isAdmin) {
sysHospitalService.changeHospital(hospitalId, String.valueOf(user1.getUserId()));
return R.ok(userService.findUserInfo(user1));
} else {
return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username));
}
}
}
sysHospitalService.changeHospital(hospitalId, String.valueOf(user.getUserId()));
return R.ok(userService.findUserInfo(user));
}
/**
* 获取当前用户全部信息
*
* @return 用户信息
*/
@GetMapping(value = { "/info" })
@GetMapping(value = {"/info"})
public R info() {
String username = SecurityUtils.getUser().getUsername();
SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));
@ -75,6 +112,7 @@ public class SysUserController {
/**
* 通过ID查询用户信息
*
* @param id ID
* @return 用户信息
*/
@ -85,6 +123,7 @@ public class SysUserController {
/**
* 查询用户信息
*
* @param query 查询条件
* @return 不为空返回用户名
*/
@ -97,6 +136,7 @@ public class SysUserController {
/**
* 删除用户信息
*
* @param ids ID
* @return R
*/
@ -110,6 +150,7 @@ public class SysUserController {
/**
* 添加用户
*
* @param userDto 用户信息
* @return success/false
*/
@ -122,6 +163,7 @@ public class SysUserController {
/**
* 更新用户信息
*
* @param userDto 用户信息
* @return R
*/
@ -129,23 +171,39 @@ public class SysUserController {
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_user_edit')")
public R updateUser(@Valid @RequestBody UserDTO userDto) {
String hospitalId = sysHospitalService.getCurrentHospital();
userDto.setHospitalId(Long.valueOf(hospitalId));
Boolean b = userService.updateUser(userDto);
return R.ok(b);
}
/**
* 分页查询用户
* @param page 参数集
*
* @param page 参数集
* @param userDTO 查询参数列表
* @return 用户集合
*/
@PostMapping("/page")
public R getUserPage(Page page, UserDTO userDTO) {
String hospitalId = sysHospitalService.getCurrentHospital();
userDTO.setHospitalId(Long.valueOf(hospitalId));
return R.ok(userService.getUsersWithRolePage(page, userDTO));
}
/**
* 分页查询用户
*
* @return 用户集合
*/
@PostMapping("/list")
public R getUserPage(Page page, String name) {
return R.ok(userService.getUsersPage(page, name));
}
/**
* 修改个人信息
*
* @param userDto userDto
* @return success/false
*/
@ -157,6 +215,7 @@ public class SysUserController {
/**
* 导出excel 表格
*
* @param userDTO 查询条件
* @return
*/
@ -169,7 +228,8 @@ public class SysUserController {
/**
* 导入用户
* @param excelVOList 用户列表
*
* @param excelVOList 用户列表
* @param bindingResult 错误信息列表
* @return R
*/
@ -181,6 +241,7 @@ public class SysUserController {
/**
* 锁定指定用户
*
* @param username 用户名
* @return R
*/
@ -198,13 +259,14 @@ public class SysUserController {
return userService.changePassword(userDto);
}
@PostMapping("/check")
/*@PostMapping("/check")
public R check(String password) {
return userService.checkPassword(password);
}
}*/
@SysLog("管理员修改密码")
@PostMapping("/modifyPw")
@PreAuthorize("@pms.hasPermission('sys_user_modify_pw')")
public R modifyPw(UserDTO userDto) {
return userService.modifyPw(userDto);
}
@ -216,4 +278,14 @@ public class SysUserController {
return R.ok(userList);
}
@PostMapping("/getUserCount")
public R getUserCount() {
return R.ok(userService.getUserCount());
}
@PostMapping("/getCountByDate")
public R getCountByDate(String startTime, String endTime) {
return R.ok(userService.getCountByDate(startTime, endTime));
}
}

View File

@ -22,4 +22,14 @@ public interface SysHospitalMapper extends BaseMapper<SysHospital> {
boolean delHospitalManager(@Param("hospitalId") String hospitalId);
List<Map> getHospitalManager(@Param("hospitalId") String hospitalId);
boolean insertCurrentHospital(@Param("hospitalId") String hospitalId, @Param("userId") String userId);
List<Map> getCurrentHospital(@Param("userId") String userId);
boolean delCurrentHospital(@Param("userId") String userId);
List<Map> getCountByProvince();
List<Map> getCountByCity(@Param("province") String province);
}

View File

@ -34,11 +34,12 @@ public interface SysUserMapper extends BaseMapper<SysUser> {
* 分页查询用户信息含角色
* @param page 分页
* @param userDTO 查询参数
* @param dataScope
* @return list
*/
IPage<UserVO> getUserVosPage(Page page, @Param("query") UserDTO userDTO);
IPage<UserVO> getUsersPage(Page page, @Param("name") String name);
/**
* 通过ID查询用户信息
* @param id 用户ID
@ -49,11 +50,18 @@ public interface SysUserMapper extends BaseMapper<SysUser> {
/**
* 查询用户列表
* @param userDTO 查询条件
* @param dataScope 数据权限声明
* @return
*/
List<UserVO> selectVoList(@Param("query") UserDTO userDTO);
List<Map> getUserListByHospital(@Param("hospitalId") String hospitalId);
boolean deleteByIds(@Param("ids") Long[] ids);
long getUserCount();
long getUserCountSlot(@Param("start") String start, @Param("end") String end);
List<Map> getCountByDate(@Param("startTime") String startTime, @Param("endTime") String endTime);
}

View File

@ -77,4 +77,12 @@ public interface SysHospitalService extends IService<SysHospital> {
*/
List getHospitalManager(String hospitalId);
boolean changeHospital(String id, String userId);
String getCurrentHospital();
Map getCountByProvince();
Map getCountByCity(String province);
}

View File

@ -12,6 +12,7 @@ import com.rax.common.core.util.R;
import org.springframework.validation.BindingResult;
import java.util.List;
import java.util.Map;
/**
* @author lengleng
@ -34,6 +35,8 @@ public interface SysUserService extends IService<SysUser> {
*/
IPage getUsersWithRolePage(Page page, UserDTO userDTO);
IPage getUsersPage(Page page, String name);
/**
* 删除用户
* @param ids 用户
@ -121,4 +124,8 @@ public interface SysUserService extends IService<SysUser> {
List getUserListByHospital(String hospitalId);
Map getUserCount();
Map getCountByDate(String startTime, String endTime);
}

View File

@ -9,10 +9,13 @@ import com.rax.admin.api.entity.SysRole;
import com.rax.admin.mapper.SysHospitalMapper;
import com.rax.admin.service.SysHospitalService;
import com.rax.admin.service.SysRoleService;
import com.rax.common.core.constant.CacheConstants;
import com.rax.common.core.util.R;
import com.rax.common.security.service.RaxUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@ -33,6 +36,9 @@ public class SysHospitalServiceImpl extends ServiceImpl<SysHospitalMapper, SysHo
@Autowired
private SysRoleService roleService;
@Autowired
private RedisTemplate redisTemplate;
public R<SysHospital> getHospitalById(String id) {
SysHospital sysHospital = getById(id);
return R.ok(sysHospital);
@ -124,4 +130,50 @@ public class SysHospitalServiceImpl extends ServiceImpl<SysHospitalMapper, SysHo
public List getHospitalManager(String hospitalId) {
return sysHospitalMapper.getHospitalManager(hospitalId);
}
@Override
public boolean changeHospital(String id, String userId) {
if (StringUtils.hasText(id)) {
redisTemplate.opsForValue().set(CacheConstants.CURRENT_HOSPITAL + ":" + userId, id);
sysHospitalMapper.delCurrentHospital(userId);
sysHospitalMapper.insertHospitalManager(id, userId);
}
return true;
}
@Override
public String getCurrentHospital() {
RaxUser raxUser = (RaxUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String userId = String.valueOf(raxUser.getId());
String hospitalId = (String) redisTemplate.opsForValue().get(CacheConstants.CURRENT_HOSPITAL + ":" + userId);
if (!StringUtils.hasText(hospitalId)) {
List<Map> currentHospital = sysHospitalMapper.getCurrentHospital(userId);
if (currentHospital.isEmpty()) {
hospitalId = raxUser.getHospitalId() != null ? raxUser.getHospitalId().toString() : null;
} else {
hospitalId = (String) currentHospital.get(0).get("hospital_id");
}
}
return hospitalId;
}
@Override
public Map getCountByProvince() {
List<Map> list = sysHospitalMapper.getCountByProvince();
Map result = new HashMap();
for (Map map : list) {
result.put(map.get("province"), map.get("count"));
}
return result;
}
@Override
public Map getCountByCity(String province) {
List<Map> list = sysHospitalMapper.getCountByCity(province);
Map result = new HashMap();
for (Map map : list) {
result.put(map.get("city"), map.get("count"));
}
return result;
}
}

View File

@ -8,6 +8,7 @@ import com.rax.admin.api.entity.SysMessageUser;
import com.rax.admin.api.entity.SysUser;
import com.rax.admin.api.vo.SysMessageVO;
import com.rax.admin.mapper.SysMessageMapper;
import com.rax.admin.service.SysHospitalService;
import com.rax.admin.service.SysMessageService;
import com.rax.admin.service.SysMessageUserService;
import com.rax.admin.service.SysUserService;
@ -30,15 +31,19 @@ public class SysMessageServiceImpl extends ServiceImpl<SysMessageMapper, SysMess
@Autowired
private SysMessageUserService sysMessageUserService;
@Autowired
private SysHospitalService sysHospitalService;
@Override
public R saveMessage(SysMessageVO sysMessageVO) {
String hospitalId = sysHospitalService.getCurrentHospital();
SysMessage sysMessage = new SysMessage();
BeanUtils.copyProperties(sysMessageVO, sysMessage);
RaxUser raxUser = (RaxUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
sysMessage.setCreator(raxUser.getId());
SysUser sysUser = sysUserService.getById(raxUser.getId());
sysMessage.setCreatorName(sysUser.getName());
sysMessage.setHospital(raxUser.getHospitalId());
sysMessage.setHospital(Long.valueOf(hospitalId));
sysMessage.setCreateTime(DateUtil.now());
sysMessage.setUpdateTime(DateUtil.now());
boolean status = save(sysMessage);

View File

@ -39,7 +39,11 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ -74,6 +78,8 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
private final SysUserMapper userMapper;
private final SysHospitalService sysHospitalService;
/**
* 保存用户信息
*
@ -88,6 +94,7 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
sysUser.setDelFlag(CommonConstants.STATUS_NORMAL);
sysUser.setCreateBy(userDto.getUsername());
sysUser.setPassword(ENCODER.encode(userDto.getPassword()));
sysUser.setHospitalId(Long.valueOf(sysHospitalService.getCurrentHospital()));
baseMapper.insert(sysUser);
// 保存用户岗位信息
Optional.ofNullable(userDto.getPost()).ifPresent(posts -> {
@ -162,6 +169,11 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
return baseMapper.getUserVosPage(page, userDTO);
}
@Override
public IPage getUsersPage(Page page, String name) {
return baseMapper.getUsersPage(page, name);
}
/**
* 通过ID查询用户信息
*
@ -191,7 +203,8 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
}
sysUserRoleMapper.delete(Wrappers.<SysUserRole>lambdaQuery().in(SysUserRole::getUserId, CollUtil.toList(ids)));
this.removeBatchByIds(CollUtil.toList(ids));
baseMapper.deleteByIds(ids);
// this.removeBatchByIds(CollUtil.toList(ids));
return Boolean.TRUE;
}
@ -497,4 +510,47 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
List list = userMapper.getUserListByHospital(hospitalId);
return list;
}
@Override
public Map getUserCount() {
Map map = new HashMap();
long total = userMapper.getUserCount();
map.put("total", total);
LocalDate today = LocalDate.now();
long todayTotal = userMapper.getUserCountSlot(today + " 00:00:00", today + " 23:59:59");
map.put("todayTotal", todayTotal);
LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDate endOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
long weekTotal = userMapper.getUserCountSlot(startOfWeek + " 00:00:00", endOfWeek + " 23:59:59");
map.put("weekTotal", weekTotal);
LocalDate startOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
LocalDate endOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
long monthTotal = userMapper.getUserCountSlot(startOfMonth + " 00:00:00" , endOfMonth + " 23:59:59");
map.put("monthTotal", monthTotal);
Year currentYear = Year.now();
LocalDate startOfYear = currentYear.atDay(1);
LocalDate endOfYear = currentYear.atDay(currentYear.length());
long yearTotal = userMapper.getUserCountSlot(startOfYear + " 00:00:00", endOfYear + " 23:59:59");
map.put("yearTotal", yearTotal);
return map;
}
@Override
public Map getCountByDate(String startTime, String endTime) {
if (StringUtils.hasText(startTime) && StringUtils.hasText(endTime)) {
Map resultMap = new HashMap();
List <Map> resultList = userMapper.getCountByDate(startTime, endTime);
for (Map map : resultList) {
resultMap.put(map.get("date"), map.get("count"));
}
return resultMap;
} else {
return null;
}
}
}

View File

@ -1,6 +1,6 @@
server:
port: 6379
# port: 9999
# port: 6379
port: 9999
servlet:
context-path: /admin
@ -12,18 +12,18 @@ spring:
type: redis
data:
redis:
# host: 192.168.244.129
host: localhost
port: 6378
host: 192.168.65.130
# host: localhost
# port: 6378
# 数据库相关配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
# username: root
# password: root
# url: jdbc:mysql://192.168.244.129:3306/rax_backend?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true
username: root
password: Xg137839
url: jdbc:mysql://110.41.142.124:3306/rax_backend?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true
password: root
url: jdbc:mysql://192.168.65.130:3306/rax_backend?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true
# username: root
# password: Xg137839
# url: jdbc:mysql://110.41.142.124:3306/rax_backend?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true
# 定时任务属性配置
quartz:
properties:
@ -106,16 +106,18 @@ mybatis-plus:
shrink-whitespaces-in-sql: true
vital-sign:
except-database: admin,config,local
information-database: information
mongodb:
# host: 192.168.244.129:27017
# password: root
# username: root
host: localhost:27017
password: Xg137839mg
username: useradmin
host: 192.168.65.130:27017
password: root
username: root
# host: localhost:27017
# password: Xg137839mg
# username: useradmin
mysql:
# host: 192.168.244.129:3306
# host: 192.168.65.130:3306
# password: root
# username: root
host: 110.41.142.124:3306

View File

@ -69,4 +69,24 @@
where u.del_flag = 0 and hm.hospital_id = #{hospitalId};
</select>
<delete id="delCurrentHospital">
DELETE FROM sys_hospital_current where user_id = #{userId}
</delete>
<insert id="insertCurrentHospital">
INSERT INTO sys_hospital_current VALUES (#{userId}, #{hospitalId});
</insert>
<select id="getCurrentHospital" resultType="map">
SELECT hospital_id from sys_hospital_current where user_id = #{userId};
</select>
<select id="getCountByProvince" resultType="map">
select province, count(*) "count" from sys_hospital where del_flag = 0 group by province
</select>
<select id="getCountByCity" resultType="map">
select city, count(*) "count" from sys_hospital where province = #{province} and del_flag = 0 group by city
</select>
</mapper>

View File

@ -117,6 +117,8 @@
LEFT JOIN sys_dept d ON d.dept_id = u.dept_id
<where>
u.del_flag = '0'
and
u.hospital_id = #{query.hospitalId}
<if test="query.name != null and query.name != ''">
<bind name="nameLike" value="'%' + query.name + '%'"/>
AND u.name LIKE #{nameLike}
@ -139,6 +141,40 @@
</if>
</select>
<select id="getUsersPage" resultMap="baseResultMap">
SELECT
u.user_id,
u.username,
u.password,
u.salt,
u.phone,
u.avatar,
u.wx_openid,
u.qq_openid,
u.dept_id,
u.create_by,
u.create_time ucreate_time,
u.update_time uupdate_time,
u.del_flag,
u.lock_flag,
u.nickname,
u.name,
u.email,
d.name dept_name
FROM
sys_user u
LEFT JOIN sys_dept d ON d.dept_id = u.dept_id
<where>
u.del_flag = '0'
<if test="name != null and name != ''">
<bind name="nameLike" value="'%' + name + '%'"/>
AND u.name LIKE #{nameLike}
</if>
</where>
ORDER BY u.create_time DESC
</select>
<select id="selectVoList" resultMap="baseResultMap">
SELECT
u.user_id,
@ -183,4 +219,38 @@
FROM sys_user
WHERE del_flag = 0 AND hospital_id = #{hospitalId} ORDER BY create_time DESC;
</select>
<update id="deleteByIds">
update sys_user set del_flag = 1
where
<if test="ids != null and ids.length != 0">
<foreach item="item" index="index" collection="ids"
open="user_id in (" separator="," close=")" nullable="false">
#{item}
</foreach>
</if>
</update>
<select id="getUserCount" resultType="long">
select count(*)
from sys_user
where del_flag = 0
</select>
<select id="getUserCountSlot" resultType="long">
select count(*)
from sys_user
where del_flag = 0 and create_time <![CDATA[ >= ]]> #{start} and create_time <![CDATA[ <= ]]> #{end}
</select>
<select id="getCountByDate" resultType="map">
select DATE_FORMAT(create_time, '%Y-%m-%d') "date", count(*) "count" from sys_user
where
del_flag = 0
and create_time <![CDATA[ >= ]]> #{startTime}
and create_time <![CDATA[ <= ]]> #{endTime}
GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')
ORDER BY DATE_FORMAT(create_time, '%Y-%m-%d') asc;
</select>
</mapper>

View File

@ -1,9 +1,9 @@
package com.rax.vital.config;
import com.rax.vital.handler.AddMedicineHandler;
import com.rax.vital.handler.ChatHandler;
import com.rax.vital.handler.MachineFeedbackHandler;
import com.rax.vital.handler.MedicineHandler;
import com.rax.vital.handler.mysql.AddMedicineHandler;
import com.rax.vital.handler.mysql.ChatHandler;
import com.rax.vital.handler.mysql.MachineFeedbackHandler;
import com.rax.vital.handler.mysql.MedicineHandler;
import com.rax.vital.interceptor.WebSocketInterceptors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -31,21 +31,25 @@ public class WebSocketConfig implements WebSocketConfigurer {
@Bean
public WebSocketHandler medicineHandler() {
return new MedicineHandler();
// return new MedicineHandler();
}
@Bean
public WebSocketHandler chatHandler() {
return new ChatHandler();
// return new ChatHandler();
}
@Bean
public WebSocketHandler addMedicineHandler() {
return new AddMedicineHandler();
// return new AddMedicineHandler();
}
@Bean
public WebSocketHandler machineHandler() {
return new MachineFeedbackHandler();
// return new MachineFeedbackHandler();
}
@Bean

View File

@ -0,0 +1,35 @@
package com.rax.vital.datasource;
import lombok.Getter;
public abstract class CustomDataSource {
// 地址
protected String host;
// 密码
protected String password;
// 账户
protected String username;
// 数据库
protected String database;
// 被使用的数量
@Getter
protected int count = 0;
public synchronized void increaseCount() {
count++;
}
public synchronized void decreaseCount() {
count--;
}
public abstract boolean open();
public abstract void close();
public abstract <T> T getConnection();
}

View File

@ -14,21 +14,7 @@ import java.util.concurrent.TimeUnit;
/**
* mongoDB连接工具类
*/
public class MongoDBSource {
// 地址
private String host;
// 密码
private String password;
// 用户名称
private String username;
private static final String authenticationDatabase = "admin";
// 数据库名称
private String database;
public class MongoDBSource extends CustomDataSource {
// mongo的客户端
private MongoClient mongoClient;
@ -37,10 +23,6 @@ public class MongoDBSource {
private SimpleMongoClientDatabaseFactory simpleMongoClientDatabaseFactory;
// 被使用的数量
@Getter
private int count = 0;
public MongoDBSource(String host, String password, String username, String database) {
this.host = host;
this.password = password;
@ -48,28 +30,35 @@ public class MongoDBSource {
this.database = database;
}
public void open() {
MongoClientSettings.Builder mongoBuilder = MongoClientSettings.builder();
// mongodb://账户:密码@ip:端口/数据库名?authSource=admin
String connectionUrl = "mongodb://" + this.username + ":" + this.password + "@" + this.host + "/" + this.database + "?authSource=admin";
mongoBuilder.applyConnectionString(new ConnectionString(connectionUrl));
mongoBuilder.applyToConnectionPoolSettings(builder -> {
// 允许的最大连接数
builder.maxSize(120);
// 最小连接数
builder.minSize(1);
// 池连接可以存活的最长时间零值表示寿命没有限制超过其生命周期的池连接将被关闭并在必要时由新连接替换
builder.maxConnectionLifeTime(0, TimeUnit.SECONDS);
// 池连接的最大空闲时间零值表示对空闲时间没有限制超过其空闲时间的池连接将被关闭并在必要时由新连接替换
builder.maxConnectionIdleTime(6, TimeUnit.MINUTES);
// 默认最大连接时间120s;
builder.maxWaitTime(60000, TimeUnit.MILLISECONDS);
});
mongoClient = MongoClients.create(mongoBuilder.build(), SpringDataMongoDB.driverInformation());
simpleMongoClientDatabaseFactory = new SimpleMongoClientDatabaseFactory(mongoClient, database);
public boolean open() {
boolean status = true;
try {
MongoClientSettings.Builder mongoBuilder = MongoClientSettings.builder();
// mongodb://账户:密码@ip:端口/数据库名?authSource=admin
String connectionUrl = "mongodb://" + this.username + ":" + this.password + "@" + this.host + "/" + this.database + "?authSource=admin";
mongoBuilder.applyConnectionString(new ConnectionString(connectionUrl));
mongoBuilder.applyToConnectionPoolSettings(builder -> {
// 允许的最大连接数
builder.maxSize(120);
// 最小连接数
builder.minSize(1);
// 池连接可以存活的最长时间零值表示寿命没有限制超过其生命周期的池连接将被关闭并在必要时由新连接替换
builder.maxConnectionLifeTime(0, TimeUnit.SECONDS);
// 池连接的最大空闲时间零值表示对空闲时间没有限制超过其空闲时间的池连接将被关闭并在必要时由新连接替换
builder.maxConnectionIdleTime(6, TimeUnit.MINUTES);
// 默认最大连接时间120s;
builder.maxWaitTime(60000, TimeUnit.MILLISECONDS);
});
mongoClient = MongoClients.create(mongoBuilder.build(), SpringDataMongoDB.driverInformation());
simpleMongoClientDatabaseFactory = new SimpleMongoClientDatabaseFactory(mongoClient, database);
} catch (Exception e) {
e.printStackTrace();
status = false;
}
return status;
}
public MongoTemplate getTemplate() {
public MongoTemplate getConnection() {
template = new MongoTemplate(simpleMongoClientDatabaseFactory);
return template;
}
@ -78,12 +67,4 @@ public class MongoDBSource {
mongoClient.close();
}
public synchronized void increaseCount() {
count++;
}
public synchronized void decreaseCount() {
count--;
}
}

View File

@ -10,19 +10,7 @@ import java.sql.Connection;
/**
* mySQL连接工具类
*/
public class MySQLSource {
// 地址
private String host;
// 密码
private String password;
// 账户
private String username;
// 数据库
private String database;
public class MySQLSource extends CustomDataSource {
// 数据库驱动
private String driver = "com.mysql.cj.jdbc.Driver";
@ -48,16 +36,23 @@ public class MySQLSource {
}
@SneakyThrows
public void open() {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://" + this.host + "/" + this.database);
dataSource.setDriverClassName(driver);
dataSource.setUsername(this.username);
dataSource.setPassword(this.password);
dataSource.setMinIdle(10);
dataSource.setMaxActive(120);
dataSource.setMaxWait(60000);
druidPooledConnection = dataSource.getConnection();
public boolean open() {
boolean status = true;
try {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://" + this.host + "/" + this.database);
dataSource.setDriverClassName(driver);
dataSource.setUsername(this.username);
dataSource.setPassword(this.password);
dataSource.setMinIdle(10);
dataSource.setMaxActive(120);
dataSource.setMaxWait(60000);
druidPooledConnection = dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
status = false;
}
return status;
}
public Connection getConnection() {
@ -75,11 +70,4 @@ public class MySQLSource {
}
}
public synchronized void increaseCount() {
count++;
}
public synchronized void decreaseCount() {
count--;
}
}

View File

@ -1,7 +1,7 @@
package com.rax.vital.handler;
import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.VitalSignTimer;
import com.rax.vital.timer.VitalSignTimerWS;
import com.rax.vital.util.DatabaseNameUtil;
import com.rax.vital.util.GetHttpParamUtil;
import jakarta.annotation.Resource;
@ -21,14 +21,14 @@ import java.util.Map;
*/
public class AddMedicineHandler implements WebSocketHandler {
@Resource
private VitalSignTimer vitalSignTimer;
private VitalSignTimerWS vitalSignTimerWS;
@Resource
private OAuth2AuthorizationService authorizationService;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
vitalSignTimer.setWSAIFlagSession(session);
vitalSignTimerWS.setWSAIFlagSession(session);
}
@Override
@ -47,7 +47,7 @@ public class AddMedicineHandler implements WebSocketHandler {
// yyyyMMdd
String date = jsonObject.getString("date");
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
vitalSignTimer.changeWSAIFlag(databaseName, username, session, jsonObject.getString("flag"),
vitalSignTimerWS.changeWSAIFlag(databaseName, username, session, jsonObject.getString("flag"),
jsonObject.getString("medicine"), jsonObject.getString("value"));
}
@ -58,7 +58,7 @@ public class AddMedicineHandler implements WebSocketHandler {
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
vitalSignTimer.removeWSAIFlagSession(session);
vitalSignTimerWS.removeWSAIFlagSession(session);
System.out.println(this.getClass().getName() + " Connection closed:" + closeStatus.getReason());
}

View File

@ -43,8 +43,6 @@ public class ChatHandler implements WebSocketHandler {
// 消息内容
String msg = jsonObject.getString("msg");
chatService.sendMessage(username, patientName, idNum, date, session, msg);
} else {
}
}
@ -54,7 +52,7 @@ public class ChatHandler implements WebSocketHandler {
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
chatService.stopTaskMongo(session.getId());
chatService.stopTask(session.getId());
}
@Override

View File

@ -1,7 +1,7 @@
package com.rax.vital.handler;
import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.VitalSignTimer;
import com.rax.vital.timer.VitalSignTimerWS;
import com.rax.vital.util.DatabaseNameUtil;
import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
@ -18,11 +18,11 @@ public class MachineFeedbackHandler implements WebSocketHandler {
private OAuth2AuthorizationService authorizationService;
@Resource
private VitalSignTimer vitalSignTimer;
private VitalSignTimerWS vitalSignTimerWS;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
vitalSignTimer.setMachineSessionMap(session);
vitalSignTimerWS.setMachineSessionMap(session);
}
@Override
@ -30,14 +30,14 @@ public class MachineFeedbackHandler implements WebSocketHandler {
JSONObject jsonObject = JSONObject.parseObject((String) message.getPayload());
// 病人名
String patientName = jsonObject.getString("patientName");
// 病人身份证
// 病人身份证住院号
String idNum = jsonObject.getString("idNum");
// yyyyMMdd
String date = jsonObject.getString("date");
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
String code = jsonObject.getString("code");
vitalSignTimer.sendMachineFlag(databaseName, code, session);
vitalSignTimerWS.sendMachineFlag(databaseName, code, session);
}
@Override
@ -46,7 +46,7 @@ public class MachineFeedbackHandler implements WebSocketHandler {
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
vitalSignTimer.removeMachineSessionMap(session);
vitalSignTimerWS.removeMachineSessionMap(session);
System.out.println(this.getClass().getName() + " Connection closed:" + closeStatus.getReason());
}

View File

@ -2,19 +2,22 @@ package com.rax.vital.handler;
import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.VitalSignTimer;
import com.rax.vital.timer.VitalSignTimerWS;
import com.rax.vital.util.DatabaseNameUtil;
import com.rax.vital.util.GetHttpParamUtil;
import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* 生命体征和标志位信息
@ -22,13 +25,19 @@ import java.util.Map;
public class MedicineHandler implements WebSocketHandler {
@Resource
private VitalSignTimer vitalSignTimer;
private VitalSignTimerWS vitalSignTimerWS;
@Resource
private OAuth2AuthorizationService authorizationService;
private static final long HEARTBEAT_INTERVAL = 30; // 心跳间隔秒数
private ScheduledExecutorService scheduler;
private ScheduledFuture<?> heartbeatTask;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
scheduler = Executors.newScheduledThreadPool(1);
heartbeatTask = scheduler.scheduleAtFixedRate(() -> sendPing(session), 0, HEARTBEAT_INTERVAL, TimeUnit.SECONDS);
}
@Override
@ -45,7 +54,7 @@ public class MedicineHandler implements WebSocketHandler {
String idNum = jsonObject.getString("idNum");
String date = jsonObject.getString("date");
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
vitalSignTimer.createAndSendWSMessageMongo(databaseName, username, session);
vitalSignTimerWS.createAndSendWSMessageMongo(databaseName, username, session);
}
@Override
@ -56,11 +65,25 @@ public class MedicineHandler implements WebSocketHandler {
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
System.out.println("MedicineHandler Connection closed:" + closeStatus.getReason());
vitalSignTimer.stopTimerTaskMongo(session.getId());
if (heartbeatTask != null) {
heartbeatTask.cancel(true);
}
if (scheduler != null) {
scheduler.shutdown();
}
vitalSignTimerWS.stopTimerTask(session.getId());
}
@Override
public boolean supportsPartialMessages() {
return false;
}
private void sendPing(WebSocketSession session) {
try {
session.sendMessage(new PingMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,69 @@
package com.rax.vital.handler.mysql;
import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.VitalSignTimerWS;
import com.rax.vital.util.DatabaseNameUtil;
import com.rax.vital.util.GetHttpParamUtil;
import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import java.net.URLDecoder;
import java.util.Map;
/**
* 网站发送给仪器给药信息
*/
public class AddMedicineHandler implements WebSocketHandler {
@Resource
private VitalSignTimerWS vitalSignTimerWS;
@Resource
private OAuth2AuthorizationService authorizationService;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
vitalSignTimerWS.setWSAIFlagSession(session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
String decode = URLDecoder.decode(session.getUri().getQuery());
Map params = GetHttpParamUtil.getParams(decode);
String token = (String) params.get("token");
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
String username = authorization.getPrincipalName();
JSONObject jsonObject = JSONObject.parseObject((String) message.getPayload());
// 病人名
String patientName = jsonObject.getString("patientName");
// 病人身份证
String idNum = jsonObject.getString("idNum");
// yyyyMMdd
String date = jsonObject.getString("date");
String databaseName = patientName + idNum;
vitalSignTimerWS.changeWSAIFlag(databaseName, username, session, jsonObject.getString("flag"),
jsonObject.getString("medicine"), jsonObject.getString("value"));
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
vitalSignTimerWS.removeWSAIFlagSession(session);
System.out.println(this.getClass().getName() + " Connection closed:" + closeStatus.getReason());
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}

View File

@ -0,0 +1,62 @@
package com.rax.vital.handler.mysql;
import com.alibaba.fastjson.JSONObject;
import com.rax.vital.medicine.service.ChatService;
import com.rax.vital.util.GetHttpParamUtil;
import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import java.net.URLDecoder;
import java.util.Map;
public class ChatHandler implements WebSocketHandler {
@Resource
private OAuth2AuthorizationService authorizationService;
@Resource
private ChatService chatService;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
String decode = URLDecoder.decode(session.getUri().getQuery());
Map params = GetHttpParamUtil.getParams(decode);
String token = (String) params.get("token");
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (authorization != null) {
String username = authorization.getPrincipalName();
String payload = (String) message.getPayload();
JSONObject jsonObject = JSONObject.parseObject(payload);
String patientName = jsonObject.getString("patientName");
String idNum = jsonObject.getString("idNum");
String date = jsonObject.getString("date");
// 消息内容
String msg = jsonObject.getString("msg");
chatService.sendMessageMysql(username, patientName, idNum, date, session, msg);
}
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
chatService.stopTask(session.getId());
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}

View File

@ -0,0 +1,57 @@
package com.rax.vital.handler.mysql;
import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.VitalSignTimerWS;
import com.rax.vital.util.DatabaseNameUtil;
import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
/**
* 仪器获取网站给药信息
*/
public class MachineFeedbackHandler implements WebSocketHandler {
@Resource
private OAuth2AuthorizationService authorizationService;
@Resource
private VitalSignTimerWS vitalSignTimerWS;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
vitalSignTimerWS.setMachineSessionMap(session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
JSONObject jsonObject = JSONObject.parseObject((String) message.getPayload());
// 病人名
String patientName = jsonObject.getString("patientName");
// 病人身份证住院号
String idNum = jsonObject.getString("idNum");
// yyyyMMdd
String date = jsonObject.getString("date");
String databaseName = patientName + idNum;
String code = jsonObject.getString("code");
vitalSignTimerWS.sendMachineFlag(databaseName, code, session);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
vitalSignTimerWS.removeMachineSessionMap(session);
System.out.println(this.getClass().getName() + " Connection closed:" + closeStatus.getReason());
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}

View File

@ -0,0 +1,84 @@
package com.rax.vital.handler.mysql;
import com.alibaba.fastjson.JSONObject;
import com.rax.vital.timer.VitalSignTimerWS;
import com.rax.vital.util.DatabaseNameUtil;
import com.rax.vital.util.GetHttpParamUtil;
import jakarta.annotation.Resource;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.web.socket.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class MedicineHandler implements WebSocketHandler {
@Resource
private VitalSignTimerWS vitalSignTimerWS;
@Resource
private OAuth2AuthorizationService authorizationService;
private static final long HEARTBEAT_INTERVAL = 30; // 心跳间隔秒数
private ScheduledExecutorService scheduler;
private ScheduledFuture<?> heartbeatTask;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// scheduler = Executors.newScheduledThreadPool(1);
// heartbeatTask = scheduler.scheduleAtFixedRate(() -> sendPing(session), 0, HEARTBEAT_INTERVAL, TimeUnit.SECONDS);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
String decode = URLDecoder.decode(session.getUri().getQuery());
Map params = GetHttpParamUtil.getParams(decode);
String token = (String) params.get("token");
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
String username = authorization.getPrincipalName();
String payload = (String) message.getPayload();
JSONObject jsonObject = JSONObject.parseObject(payload);
String patientName = jsonObject.getString("patientName");
String idNum = jsonObject.getString("idNum");
String databaseName = patientName + idNum;
vitalSignTimerWS.createAndSendMessageMySQL(databaseName, username, session);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
System.out.println("Error: " + exception.getMessage());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
System.out.println("MedicineHandler Connection closed:" + closeStatus.getReason());
if (heartbeatTask != null) {
heartbeatTask.cancel(true);
}
if (scheduler != null) {
scheduler.shutdown();
}
vitalSignTimerWS.stopTimerTask(session.getId());
}
@Override
public boolean supportsPartialMessages() {
return false;
}
private void sendPing(WebSocketSession session) {
try {
session.sendMessage(new PingMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -55,7 +55,7 @@ public class WSChannelInterceptor implements ChannelInterceptor {
|| StompCommand.UNSUBSCRIBE.equals(accessor.getCommand()) || StompCommand.ABORT.equals(accessor.getCommand())) {
String simpSessionId = (String) accessor.getHeader("simpSessionId");
vitalSignTimer.stopTimerTaskMongo(simpSessionId);
chatService.stopTimerTaskMongo(simpSessionId);
chatService.stopTimerTask(simpSessionId);
}
}
return message;

View File

@ -15,14 +15,12 @@ import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* 用药
@ -96,8 +94,88 @@ public class MedicineController {
return vitalSignsService.getPatientInfo(databaseName);
}
@PostMapping("/getDatabaseList")
@PostMapping("/getPatientInfoM")
public R getPatientInfoM(String patientName, String idNum, String date) {
String databaseName = patientName + idNum;
return vitalSignsService.getPatientInfoM(databaseName);
}
/* @PostMapping("/getDatabaseList")
public R getDatabaseList() {
return vitalSignsService.getDatabaseList();
}*/
@PostMapping("/getPatientPage")
public R getPatientPage(String name, String dept, long offset, int limit) {
return R.ok(vitalSignsService.getPatientPage(name, dept, offset, limit));
}
/**
* 某月手术每天台数
*/
@PostMapping("/getSurgeryCount")
public R getSurgeryCount(String start, String end) {
return R.ok(vitalSignsService.getSurgeryCount(start, end));
}
@PostMapping("/getSurgeryCountM")
public R getSurgeryCountM(String startTime, String endTime) {
return R.ok(vitalSignsService.getSurgeryCountMysql(startTime, endTime));
}
/**
* 某月手术每天时长
*/
@PostMapping("/getSurgeryDuration")
public R getSurgeryDuration(String start, String end) {
return R.ok(vitalSignsService.getSurgeryDuration(start, end));
}
@PostMapping("/getSurgeryDurationM")
public R getSurgeryDurationM(String startTime, String endTime) {
return R.ok(vitalSignsService.getSurgeryDurationMysql(startTime, endTime));
}
/**
* 某月手术类型数量
*/
@PostMapping("/getSurgeryTypeProportion")
public R getSurgeryTypeProportion(String start, String end) {
return R.ok(vitalSignsService.getSurgeryTypeProportion(start, end));
}
@PostMapping("/getSurgeryTypeProportionM")
public R getSurgeryTypeProportionM(String startTime, String endTime) {
return R.ok(vitalSignsService.getSurgeryTypeProportionMysql(startTime, endTime));
}
/**
* 某周的麻醉和人工给药时长
*/
@PostMapping("/getSurgeryOtherDuration")
public R getSurgeryOtherDuration(String start, String end) {
return R.ok(vitalSignsService.getSurgeryOtherDuration(start, end));
}
@PostMapping("/getSurgeryOtherDurationM")
public R getSurgeryOtherDurationM(String startTime, String endTime) {
return R.ok(vitalSignsService.getSurgeryOtherDurationMysql(startTime, endTime));
}
/**
* 获取用户的手术列表
*/
@PostMapping("/getPatientSurgeryList")
public R getPatientSurgeryList(String name, String code, String surgery, String type) {
return R.ok(vitalSignsService.getPatientSurgeryList(name, code, surgery, type));
}
/**
* 根据手术表名来获取所有数据
*/
@PostMapping("/getSurgeryTableData")
public R getSurgeryTableData(String name, String code, String date, String table) {
return R.ok(vitalSignsService.getSurgeryTableData(name, code, date, table));
}
}

View File

@ -9,7 +9,9 @@ public interface ChatService {
void sendMessage(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) throws IOException;
void stopTimerTaskMongo(String simpSessionId);
void sendMessageMysql(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) throws Exception;
void stopTaskMongo(String simpSessionId);
void stopTimerTask(String simpSessionId);
void stopTask(String simpSessionId);
}

View File

@ -1,5 +1,6 @@
package com.rax.vital.medicine.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rax.common.core.util.R;
import com.rax.vital.datasource.MongoDBSource;
import org.springframework.data.mongodb.core.MongoTemplate;
@ -29,5 +30,29 @@ public interface VitalSignsService {
R getPatientInfo(String databaseName);
R getPatientInfoM(String databaseName);
R getDatabaseList();
Page getPatientPage(String name, String dept, long offset, int limit);
List getSurgeryCount(String start, String end);
List getSurgeryDuration(String start, String end);
List getSurgeryTypeProportion(String start, String end);
List getSurgeryOtherDuration(String start, String end);
List getPatientSurgeryList(String name, String code, String surgery, String type);
List getSurgeryTableData(String name, String code, String date, String table);
List getSurgeryCountMysql(String startTime, String endTime);
List getSurgeryDurationMysql(String startTime, String endTime);
List getSurgeryTypeProportionMysql(String startTime, String endTime);
List getSurgeryOtherDurationMysql(String startTime, String endTime);
}

View File

@ -55,7 +55,7 @@ public class AIMedicineServiceImpl implements AIMedicineService {
List<Map> medicineList = new ArrayList<>();
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT id, phase, `丙泊酚`, `舒芬太尼`, `瑞芬太尼`, `顺阿曲库胺`, `尼卡地平`, `艾司洛尔`, `麻黄素`, `阿托品`, time FROM `AIMedicineTable` ORDER BY time LIMIT 1;");
ResultSet resultSet = statement.executeQuery("SELECT id, phase, `丙泊酚`, `舒芬太尼`, `瑞芬太尼`, `顺阿曲库胺`, `尼卡地平`, `艾司洛尔`, `麻黄素`, `阿托品`, time FROM `aimedicinetable` ORDER BY time DESC LIMIT 1;");
while (resultSet.next()) {
Map medicine = new HashMap();
medicine.put("id", resultSet.getString("id"));
@ -68,7 +68,7 @@ public class AIMedicineServiceImpl implements AIMedicineService {
medicine.put("艾司洛尔", resultSet.getString("艾司洛尔"));
medicine.put("麻黄素", resultSet.getString("麻黄素"));
medicine.put("阿托品", resultSet.getString("阿托品"));
medicine.put("time", resultSet.getString("time"));
medicine.put("Time", resultSet.getString("time"));
medicineList.add(medicine);
}
} catch (SQLException e) {

View File

@ -7,7 +7,9 @@ import com.rax.admin.api.dto.UserInfo;
import com.rax.admin.api.feign.RemoteUserService;
import com.rax.common.core.constant.SecurityConstants;
import com.rax.common.core.util.R;
import com.rax.vital.datasource.CustomDataSource;
import com.rax.vital.datasource.MongoDBSource;
import com.rax.vital.datasource.MySQLSource;
import com.rax.vital.medicine.service.ChatService;
import com.rax.vital.util.DatabaseNameUtil;
import org.bson.Document;
@ -22,6 +24,7 @@ import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
@ -35,7 +38,7 @@ public class ChatServiceImpl implements ChatService {
@Autowired
private RemoteUserService remoteUserService;
private static final Map<String, MongoDBSource> datasourceMap = new HashMap<>();
private static final Map<String, CustomDataSource> datasourceMap = new HashMap<>();
private static final Map<String, Map<String, WebSocketSession>> databaseSessionMap = new HashMap<>();
@ -53,9 +56,21 @@ public class ChatServiceImpl implements ChatService {
@Value("${vital-sign.mongodb.password}")
private String mongoPassword;
// mysql地址
@Value("${vital-sign.mysql.host}")
private String mysqlHost;
// mysql用户名
@Value("${vital-sign.mysql.username}")
private String mysqlUsername;
// mysql用户密码
@Value("${vital-sign.mysql.password}")
private String mysqlPassword;
@Override
public void sendMessage(String username, String patientName, String idNum, String date, String simpSessionId, String msg) {
MongoDBSource mongoDBSource = datasourceMap.get(simpSessionId);
CustomDataSource mongoDBSource = datasourceMap.get(simpSessionId);
if (mongoDBSource == null) {
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName);
@ -70,7 +85,7 @@ public class ChatServiceImpl implements ChatService {
Map param = new HashMap();
MongoTemplate template = mongoDBSource.getTemplate();
MongoTemplate template = mongoDBSource.getConnection();
Document document = new Document();
document.put("content", msg);
param.put("content", msg);
@ -90,7 +105,7 @@ public class ChatServiceImpl implements ChatService {
@Override
public void sendMessage(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) throws IOException {
MongoDBSource mongoDBSource = datasourceMap.get(session.getId());
CustomDataSource mongoDBSource = datasourceMap.get(session.getId());
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
synchronized (username) {
if (mongoDBSource == null) {
@ -119,7 +134,7 @@ public class ChatServiceImpl implements ChatService {
if (StringUtils.hasText(msg)) {
JSONObject param = new JSONObject();
MongoTemplate template = mongoDBSource.getTemplate();
MongoTemplate template = mongoDBSource.getConnection();
Document document = new Document();
document.put("content", msg);
param.put("content", msg);
@ -143,8 +158,102 @@ public class ChatServiceImpl implements ChatService {
}
@Override
public synchronized void stopTimerTaskMongo(String simpSessionId) {
MongoDBSource mongoDBSource = datasourceMap.get(simpSessionId);
public void sendMessageMysql(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) {
CustomDataSource dataSource = datasourceMap.get(session.getId());
String databaseName = patientName + idNum;
synchronized (username) {
if (dataSource == null) {
dataSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, databaseName);
boolean status = dataSource.open();
if (status) {
datasourceMap.put(session.getId(), dataSource);
sessionDatabaseMap.put(session.getId(), databaseName);
Map<String, WebSocketSession> sessionMap = databaseSessionMap.get(databaseName);
if (sessionMap == null) {
sessionMap = new HashMap();
sessionMap.put(session.getId(), session);
databaseSessionMap.put(databaseName, sessionMap);
} else {
if (!sessionMap.containsKey(session.getId())) {
sessionMap.put(session.getId(), session);
}
}
} else {
JSONObject jsonObject = new JSONObject();
jsonObject.put("status", 1);
jsonObject.put("msg", "数据库未创建, 请重新连接。");
try {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
session.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return;
}
}
}
UserDTO userDTO = new UserDTO();
userDTO.setUsername(username);
R<UserInfo> info = remoteUserService.info(userDTO, SecurityConstants.FROM_IN);
UserInfo userInfo = info.getData();
if (StringUtils.hasText(msg)) {
JSONObject param = new JSONObject();
Connection connection = dataSource.getConnection();
try {
Statement statement = connection.createStatement();
String sql = "CREATE TABLE `t_chat` (\n" +
" `id` int NOT NULL AUTO_INCREMENT,\n" +
" `content` varchar(5000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `create_time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `create_user` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `create_name` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `deleted` bit(1) NULL DEFAULT NULL,\n" +
" `revoked` bit(1) NULL DEFAULT NULL,\n" +
" PRIMARY KEY (`id`) USING BTREE\n" +
") ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;";
statement.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
}
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement("INSERT INTO t_chat (content, create_time, create_user, create_name, deleted, revoked) VALUES (?, ?, ?, ?, ?, ?)");
preparedStatement.setString(1, msg);
param.put("content", msg);
String now = DateUtil.now();
preparedStatement.setString(2, now);
param.put("createTime", now);
preparedStatement.setString(3, username);
String name = userInfo.getSysUser().getName();
preparedStatement.setString(4, name);
param.put("createName", name);
preparedStatement.setInt(5, 0);
preparedStatement.setInt(6, 0);
preparedStatement.execute();
} catch (SQLException e) {
throw new RuntimeException(e);
}
Map<String, WebSocketSession> sessionMap = databaseSessionMap.get(databaseName);
for (Map.Entry<String, WebSocketSession> entry : sessionMap.entrySet()) {
WebSocketSession value = entry.getValue();
try {
value.sendMessage(new TextMessage(param.toJSONString().getBytes()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
@Override
public synchronized void stopTimerTask(String simpSessionId) {
CustomDataSource mongoDBSource = datasourceMap.get(simpSessionId);
if (mongoDBSource != null) {
mongoDBSource.close();
datasourceMap.remove(simpSessionId);
@ -152,8 +261,8 @@ public class ChatServiceImpl implements ChatService {
}
@Override
public synchronized void stopTaskMongo(String simpSessionId) {
MongoDBSource mongoDBSource = datasourceMap.get(simpSessionId);
public synchronized void stopTask(String simpSessionId) {
CustomDataSource mongoDBSource = datasourceMap.get(simpSessionId);
if (mongoDBSource != null) {
mongoDBSource.close();
datasourceMap.remove(simpSessionId);

View File

@ -42,7 +42,7 @@ public class DoctorMedicineServiceImpl implements DoctorMedicineService {
List<Map> medicineList = new ArrayList<>();
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT id, phase, `丙泊酚`, `舒芬太尼`, `瑞芬太尼`, `顺阿曲库胺`, `尼卡地平`, `艾司洛尔`, `麻黄素`, `阿托品`, time FROM `DoctorMedicineTable` ORDER BY time LIMIT 1;");
ResultSet resultSet = statement.executeQuery("SELECT id, phase, `丙泊酚`, `舒芬太尼`, `瑞芬太尼`, `顺阿曲库胺`, `尼卡地平`, `艾司洛尔`, `麻黄素`, `阿托品`, time FROM `doctormedicinetable` ORDER BY time DESC LIMIT 1;");
while (resultSet.next()) {
Map medicine = new HashMap();
medicine.put("id", resultSet.getString("id"));
@ -55,7 +55,7 @@ public class DoctorMedicineServiceImpl implements DoctorMedicineService {
medicine.put("艾司洛尔", resultSet.getString("艾司洛尔"));
medicine.put("麻黄素", resultSet.getString("麻黄素"));
medicine.put("阿托品", resultSet.getString("阿托品"));
medicine.put("time", resultSet.getString("time"));
medicine.put("Time", resultSet.getString("time"));
medicineList.add(medicine);
}
} catch (SQLException e) {

View File

@ -97,39 +97,55 @@ public class FlagServiceImpl implements FlagService {
Map allFlag = new HashMap();
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM `EndFlagTable` ORDER BY time LIMIT 1;");
// 0代表手术未开始或已结束1代表手术进行中
ResultSet resultSet = statement.executeQuery("SELECT * FROM `endflagtable` ORDER BY time DESC LIMIT 1;");
List<Map> endFlagList = new ArrayList<>();
while (resultSet.next()) {
Map flag = new HashMap();
flag.put("id", resultSet.getString(0));
flag.put("flag", resultSet.getString(1));
flag.put("time", resultSet.getString(2));
flag.put("id", resultSet.getString(1));
flag.put("Flag", resultSet.getString(2));
flag.put("Time", resultSet.getString(3));
endFlagList.add(flag);
}
allFlag.put("endFlag", endFlagList);
allFlag.put("endflagtable", endFlagList);
ResultSet aiRe = statement.executeQuery("SELECT * FROM `AIFlagTable` ORDER BY time LIMIT 1;");
// Flag默认为10代表诱导期给药1代表维持期AI给药2代表维持期医生给药
// ConvertFlag默认为00代表无需切换1代表由AI给药转为医生给药
ResultSet aiRe = statement.executeQuery("SELECT * FROM `aiflagtable` ORDER BY time DESC LIMIT 1;");
List<Map> aiFlagList = new ArrayList<>();
while (aiRe.next()) {
Map flag = new HashMap();
flag.put("id", aiRe.getString(0));
flag.put("flag", aiRe.getString(1));
flag.put("convertFlag", aiRe.getString(2));
flag.put("time", aiRe.getString(3));
flag.put("id", aiRe.getString(1));
flag.put("Flag", aiRe.getString(2));
flag.put("ConvertFlag", aiRe.getString(3));
flag.put("Time", aiRe.getString(4));
aiFlagList.add(flag);
}
allFlag.put("aiFlag", aiFlagList);
allFlag.put("aiflagtable", aiFlagList);
ResultSet reRe = statement.executeQuery("SELECT * FROM `ReFlagTable` ORDER BY time LIMIT 1;");
// 诱导期标志符 0是诱导期 1是维持期
ResultSet reRe = statement.executeQuery("SELECT * FROM `reflagtable` ORDER BY time DESC LIMIT 1;");
List<Map> reFlagList = new ArrayList<>();
while (reRe.next()) {
Map flag = new HashMap();
flag.put("id", reRe.getString(0));
flag.put("flag", reRe.getString(1));
flag.put("time", reRe.getString(2));
flag.put("id", reRe.getString(1));
flag.put("Flag", reRe.getString(2));
flag.put("Time", reRe.getString(3));
reFlagList.add(flag);
}
allFlag.put("reFlag", reFlagList);
allFlag.put("reflagtable", reFlagList);
// Flag默认为1: 0代表泵站通讯正常1代表泵站通讯异常
ResultSet link = statement.executeQuery("SELECT * FROM `linktable` ORDER BY time DESC LIMIT 1;");
List<Map> linkFlagList = new ArrayList<>();
while (link.next()) {
Map flag = new HashMap();
flag.put("id", link.getString(1));
flag.put("Flag", link.getString(2));
flag.put("Time", link.getString(3));
linkFlagList.add(flag);
}
allFlag.put("linktable", linkFlagList);
} catch (SQLException e) {
throw new RuntimeException(e);

View File

@ -41,7 +41,7 @@ public class RevulsionServiceImpl implements RevulsionService {
List<Map> medicineList = new ArrayList<>();
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT id, phase, `丙泊酚`, `舒芬太尼`, `瑞芬太尼`, `顺阿曲库胺`, `尼卡地平`, `艾司洛尔`, `麻黄素`, `阿托品`, time FROM `RevulsionTable` ORDER BY time LIMIT 1;");
ResultSet resultSet = statement.executeQuery("SELECT id, phase, `丙泊酚`, `舒芬太尼`, `瑞芬太尼`, `顺阿曲库胺`, `尼卡地平`, `艾司洛尔`, `麻黄素`, `阿托品`, time FROM `revulsiontable` ORDER BY time DESC LIMIT 1;");
while (resultSet.next()) {
Map medicine = new HashMap();
medicine.put("id", resultSet.getString("id"));
@ -54,7 +54,7 @@ public class RevulsionServiceImpl implements RevulsionService {
medicine.put("艾司洛尔", resultSet.getString("艾司洛尔"));
medicine.put("麻黄素", resultSet.getString("麻黄素"));
medicine.put("阿托品", resultSet.getString("阿托品"));
medicine.put("time", resultSet.getString("time"));
medicine.put("Time", resultSet.getString("time"));
medicineList.add(medicine);
}
} catch (SQLException e) {

View File

@ -1,5 +1,6 @@
package com.rax.vital.medicine.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
@ -7,25 +8,27 @@ import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoIterable;
import com.rax.common.core.util.R;
import com.rax.vital.datasource.MongoDBSource;
import com.rax.vital.datasource.MySQLSource;
import com.rax.vital.medicine.service.VitalSignsService;
import com.rax.vital.util.DatabaseNameUtil;
import lombok.extern.slf4j.Slf4j;
import org.bson.BsonRegularExpression;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.SpringDataMongoDB;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 生命体征数据
@ -49,6 +52,18 @@ public class VitalSignServiceImpl implements VitalSignsService {
@Value("${vital-sign.except-database}")
private String exceptDatabase;
@Value("${vital-sign.information-database}")
private String informationDatabase;
@Value("${vital-sign.mysql.host}")
private String mysqlHost;
@Value("${vital-sign.mysql.password}")
private String mysqlPassword;
@Value("${vital-sign.mysql.username}")
private String mysqlUsername;
/**
* 获取生命体征最新一条数据
*
@ -87,21 +102,33 @@ public class VitalSignServiceImpl implements VitalSignsService {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT id, Phase, BIS, HR, SBP, DBP, ST, TEMP, SPO2, EtCO2, PPG, ABG, TOF, Time FROM `featuretable` ORDER BY time DESC LIMIT 1;");
while (resultSet.next()) {
Map vital = new HashMap();
Map<String, Object> vital = new HashMap();
vital.put("id", resultSet.getString("id"));
vital.put("phase", resultSet.getString("phase"));
vital.put("bis", resultSet.getString("bis"));
vital.put("hr", resultSet.getString("hr"));
vital.put("sbp", resultSet.getString("sbp"));
vital.put("dbp", resultSet.getString("dbp"));
vital.put("st", resultSet.getString("st"));
vital.put("temp", resultSet.getString("temp"));
vital.put("spo2", resultSet.getString("spo2"));
vital.put("etco2", resultSet.getString("etco2"));
vital.put("ppg", resultSet.getString("ppg"));
vital.put("abg", resultSet.getString("abg"));
vital.put("tof", resultSet.getString("tof"));
vital.put("time", resultSet.getString("time"));
vital.put("Phase", resultSet.getString("Phase"));
vital.put("BIS", resultSet.getString("BIS"));
vital.put("HR", resultSet.getString("HR"));
vital.put("SBP", resultSet.getString("SBP"));
vital.put("DBP", resultSet.getString("DBP"));
vital.put("ST", resultSet.getString("ST"));
vital.put("TEMP", resultSet.getString("TEMP"));
vital.put("SPO2", resultSet.getString("SPO2"));
vital.put("EtCO2", resultSet.getString("EtCO2"));
vital.put("PPG", resultSet.getString("PPG"));
vital.put("ABG", resultSet.getString("ABG"));
vital.put("TOF", resultSet.getString("TOF"));
vital.put("Time", resultSet.getString("Time"));
Double bis = resultSet.getDouble("BIS");
vital.put("BIS_except", bis <= 40 || bis >= 60);
Double hr = resultSet.getDouble("HR");
vital.put("HR_except", hr <= 50 || hr >= 80);
Double sbp = resultSet.getDouble("SBP");
vital.put("SBP_except", sbp <= 90 || sbp >= 120);
Double dbp = resultSet.getDouble("DBP");
vital.put("DBP_except", dbp <= 60 || dbp >= 90);
Double st = resultSet.getDouble("ST");
vital.put("ST_except", st <= -0.2 || st >= 0.2);
Double etCO2 = resultSet.getDouble("EtCO2");
vital.put("EtCO2_except", etCO2 <= 30 || etCO2 >= 45);
vitalList.add(vital);
}
} catch (SQLException e) {
@ -113,7 +140,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
public R getPatientInfo(String databaseName) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getTemplate();
MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query();
query.limit(1);
query.with(Sort.by(Sort.Order.desc("Time")));
@ -122,6 +149,41 @@ public class VitalSignServiceImpl implements VitalSignsService {
return R.ok(vitalList);
}
public R getPatientInfoM(String databaseName) {
MySQLSource mySQLSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, databaseName);
mySQLSource.open();
Connection connection = mySQLSource.getConnection();
Map map = new HashMap();
try {
Statement statement = connection.createStatement();
String sql = "SELECT `名字` , `性别`,`年龄` ,`体重`,`身高` ,`身份证号`,`是否有疾病史` , `病史类型`,`病史名称`," +
"`医院名称` ,`住院号` ,`科室`,`手术名称` ,`麻醉方式` ,`日期` \"住院时间\" " +
" FROM `patienttable` ORDER BY `日期` DESC LIMIT 1; ";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
map.put("姓名", resultSet.getString("名字"));
map.put("性别", resultSet.getString("性别"));
map.put("年龄", resultSet.getString("年龄"));
map.put("体重", resultSet.getString("体重"));
map.put("身高", resultSet.getString("身高"));
map.put("身份证号", resultSet.getString("身份证号"));
map.put("是否有疾病史", resultSet.getString("是否有疾病史"));
map.put("病史类型", resultSet.getString("病史类型"));
map.put("病史名称", resultSet.getString("病史名称"));
map.put("医院名称", resultSet.getString("医院名称"));
map.put("住院号", resultSet.getString("住院号"));
map.put("科室", resultSet.getString("科室"));
map.put("手术名称", resultSet.getString("手术名称"));
map.put("麻醉方式", resultSet.getString("麻醉方式"));
map.put("住院时间", resultSet.getString("住院时间"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return R.ok(map);
}
@Override
public R getDatabaseList() {
MongoClientSettings.Builder mongoBuilder = MongoClientSettings.builder();
@ -130,8 +192,399 @@ public class VitalSignServiceImpl implements VitalSignsService {
mongoBuilder.applyConnectionString(new ConnectionString(connectionUrl));
MongoClient mongoClient = MongoClients.create(mongoBuilder.build(), SpringDataMongoDB.driverInformation());
MongoIterable<String> databaseNames = mongoClient.listDatabaseNames();
for (String database: databaseNames) {
for (String database : databaseNames) {
}
return null;
}
public Page getPatientPage(String name, String dept, long offset, int limit) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query();
if (StringUtils.hasText(name)) {
Criteria criteria = new Criteria("姓名");
criteria.regex(new BsonRegularExpression(".*" + name + ".*"));
query.addCriteria(criteria);
}
if (StringUtils.hasText(dept)) {
Criteria criteria = new Criteria("科室");
criteria.regex(new BsonRegularExpression(dept));
query.addCriteria(criteria);
}
query.with(Sort.by(Sort.Order.desc("住院时间")));
query.skip(offset).limit(limit);
List<Map> list = template.find(query, Map.class, "patient_info");
long count = template.count(query, "patient_info");
Page page = new Page();
page.setRecords(list);
page.setTotal(count);
mongoDBSource.close();
return page;
}
@Override
public List getSurgeryCount(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>();
Criteria criteria = new Criteria("Time");
criteria.gte(start);
criteria.lte(end);
operations.add(Aggregation.match(criteria));
ProjectionOperation timeToDateOperation = Aggregation.project()
.andExpression("Time").as("Time")
.andExpression("{$toDate: '$Time'}").as("time");
operations.add(timeToDateOperation);
ProjectionOperation timeFormatOperation = Aggregation.project()
.andExpression("{ $dateToString: { format: '%Y-%m-%d', date: '$time' } }").as("time");
operations.add(timeFormatOperation);
operations.add(Aggregation.group("$time").count().as("count"));
operations.add(Aggregation.project()
.andInclude("count")
.andExpression("{$toDate: '$_id'}").as("time"));
operations.add(Aggregation.project()
.andInclude("count")
.andExpression("{ $dateToString: { format: '%d', date: '$time' } }").as("time"));
operations.add(Aggregation.sort(Sort.Direction.ASC, "time"));
TypedAggregation typedAggregation = new TypedAggregation(Map.class, operations);
AggregationResults<Map> aggregate = template.aggregate(typedAggregation, "surgery_info", Map.class);
List<Map> mappedResults = aggregate.getMappedResults();
mongoDBSource.close();
return mappedResults;
}
public List getSurgeryDuration(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>();
Criteria criteria = new Criteria("Time");
criteria.gte(start);
criteria.lte(end);
operations.add(Aggregation.match(criteria));
ProjectionOperation timeToDateOperation = Aggregation.project()
.andExpression("{$toLong: '$Surgery_duration(min)'}").as("Surgery_duration(min)")
.andExpression("{$toDate: '$Time'}").as("day");
operations.add(timeToDateOperation);
ProjectionOperation timeFormatOperation = Aggregation.project()
.andInclude("Surgery_duration(min)")
.andExpression("{ $dateToString: { format: '%Y-%m-%d', date: '$day' } }").as("time");
operations.add(timeFormatOperation);
operations.add(Aggregation.group("$time").sum("Surgery_duration(min)").as("count"));
operations.add(Aggregation.project()
.andInclude("_id")
.andExpression("count").divide(60).as("count"));
operations.add(Aggregation.project()
.andInclude("_id")
.andExpression("{$round: {'$count', 1}}").as("duration"));
operations.add(Aggregation.project()
.andInclude("duration")
.andExpression("{$toDate: '$_id'}").as("time"));
operations.add(Aggregation.project()
.andInclude("duration")
.andExpression("{ $dateToString: { format: '%d', date: '$time' } }").as("_id"));
operations.add(Aggregation.sort(Sort.Direction.ASC, "_id"));
TypedAggregation typedAggregation = new TypedAggregation(Map.class, operations);
AggregationResults<Map> aggregate = template.aggregate(typedAggregation, "surgery_info", Map.class);
List<Map> mappedResults = aggregate.getMappedResults();
mongoDBSource.close();
return mappedResults;
}
public List getSurgeryTypeProportion(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>();
Criteria criteria = new Criteria("Time");
criteria.gte(start);
criteria.lte(end);
operations.add(Aggregation.match(criteria));
operations.add(Aggregation.group("$Surgery_type").count().as("count"));
TypedAggregation typedAggregation = new TypedAggregation(Map.class, operations);
AggregationResults<Map> aggregate = template.aggregate(typedAggregation, "surgery_info", Map.class);
List<Map> mappedResults = aggregate.getMappedResults();
mongoDBSource.close();
return mappedResults;
}
public List getSurgeryOtherDuration(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>();
Criteria criteria = new Criteria("Time");
criteria.gte(start);
criteria.lte(end);
operations.add(Aggregation.match(criteria));
ProjectionOperation timeToDateOperation = Aggregation.project()
.andExpression("{$toLong: '$Aianaesthesia_duration(min)'}").as("Aianaesthesia_duration(min)")
.andExpression("{$toLong: '$Doctoranaesthesia_duration(min)'}").as("Doctoranaesthesia_duration(min)")
.andExpression("{$toDate: '$Time'}").as("time");
operations.add(timeToDateOperation);
ProjectionOperation timeFormatOperation = Aggregation.project()
.andInclude("Aianaesthesia_duration(min)")
.andInclude("Doctoranaesthesia_duration(min)")
.andExpression("{ $dateToString: { format: '%Y-%m-%d', date: '$time' } }").as("time");
operations.add(timeFormatOperation);
operations.add(Aggregation.group("$time")
.sum("Aianaesthesia_duration(min)").as("aicount")
.sum("Doctoranaesthesia_duration(min)").as("doccount"));
operations.add(Aggregation.project()
.andInclude("_id")
.andExpression("aicount").divide(60).as("aicount")
.andExpression("doccount").divide(60).as("doccount"));
operations.add(Aggregation.project()
.andInclude("_id")
.andExpression("{$round: {'$aicount', 1}}").as("aicount")
.andExpression("{$round: {'$doccount', 1}}").as("doccount"));
operations.add(Aggregation.sort(Sort.Direction.ASC, "_id"));
TypedAggregation typedAggregation = new TypedAggregation(Map.class, operations);
AggregationResults<Map> aggregate = template.aggregate(typedAggregation, "surgery_info", Map.class);
List<Map> mappedResults = aggregate.getMappedResults();
mongoDBSource.close();
return mappedResults;
}
@Override
public List getPatientSurgeryList(String name, String code, String surgery, String type) {
if (StringUtils.hasText(code)) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
if (!StringUtils.hasText(name)) {
Query query = new Query();
Criteria criteria = new Criteria("住院号");
criteria.regex(new BsonRegularExpression(code));
query.addCriteria(criteria);
List<Map> list = template.find(query, Map.class, "patient_info");
if (!list.isEmpty()) {
Map patient = list.get(0);
name = (String) patient.get("姓名");
} else {
mongoDBSource.close();
return List.of();
}
}
Query query = new Query();
String databasePrefix = DatabaseNameUtil.encrypt(name) + "_" + DatabaseNameUtil.encrypt(code) + "_";
Criteria criteria = new Criteria("Databasename");
criteria.regex(new BsonRegularExpression("^" + databasePrefix));
query.addCriteria(criteria);
if (StringUtils.hasText(surgery)) {
Criteria surgeryCriteria = new Criteria("Surgery_name");
surgeryCriteria.regex(new BsonRegularExpression(surgery));
query.addCriteria(surgeryCriteria);
}
if (StringUtils.hasText(type)) {
Criteria anesthesiaCriteria = new Criteria("Anesthesia_way");
anesthesiaCriteria.regex(new BsonRegularExpression(type));
query.addCriteria(anesthesiaCriteria);
}
query.with(Sort.by(Sort.Order.desc("Time")));
List<Map> surgeryInfoList = template.find(query, Map.class, "surgery_info");
mongoDBSource.close();
return surgeryInfoList;
} else {
return List.of();
}
}
@Override
public List getSurgeryTableData(String name, String code, String date, String table) {
if (StringUtils.hasText(code)) {
if (!StringUtils.hasText(name)) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query();
Criteria criteria = new Criteria("住院号");
criteria.regex(new BsonRegularExpression(code));
query.addCriteria(criteria);
List<Map> list = template.find(query, Map.class, "patient_info");
if (!list.isEmpty()) {
Map patient = list.get(0);
name = (String) patient.get("姓名");
}
mongoDBSource.close();
}
String database = DatabaseNameUtil.encrypt(name) + "_" + DatabaseNameUtil.encrypt(code) + "_" + date;
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query();
query.with(Sort.by(Sort.Order.asc("_id")));
List<Map> list = template.find(query, Map.class, table);
mongoDBSource.close();
return list;
} else {
return new ArrayList<>();
}
}
@Override
public List getSurgeryCountMysql(String startTime, String endTime) {
List<Map> list = new ArrayList<>();
MySQLSource mySQLSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, informationDatabase);
mySQLSource.open();
Connection connection = mySQLSource.getConnection();
String sql = "select date_format( Time,'%Y-%m-%d') \"date\", count(*) \"count\" " +
" from surgery_info " +
" where " +
" Time >= ? and Time <= ? " +
" GROUP BY date_format( Time,'%Y-%m-%d') " +
" ORDER BY date_format( Time,'%Y-%m-%d') ";
try {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, startTime);
statement.setString(2, endTime);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Map obj = new HashMap();
obj.put("date", resultSet.getString("date"));
obj.put("count", resultSet.getString("count"));
list.add(obj);
}
} catch (SQLException e) {
mySQLSource.close();
throw new RuntimeException(e);
}
mySQLSource.close();
return list;
}
@Override
public List getSurgeryDurationMysql(String startTime, String endTime) {
List<Map> list = new ArrayList<>();
MySQLSource mySQLSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, informationDatabase);
mySQLSource.open();
Connection connection = mySQLSource.getConnection();
String sql = "select date_format(Time, '%Y-%m-%d') \"date\", round(sum(`Surgery_duration(min)`) / 60, 2) \"duration\" " +
" from surgery_info " +
" where " +
" Time >= ? and Time <= ? " +
" GROUP BY date_format( Time,'%Y-%m-%d') " +
" ORDER BY date_format( Time,'%Y-%m-%d') ";
try {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, startTime);
statement.setString(2, endTime);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Map obj = new HashMap();
obj.put("date", resultSet.getString("date"));
obj.put("duration", resultSet.getString("duration"));
list.add(obj);
}
} catch (SQLException e) {
mySQLSource.close();
throw new RuntimeException(e);
}
mySQLSource.close();
return list;
}
@Override
public List getSurgeryTypeProportionMysql(String startTime, String endTime) {
List<Map> list = new ArrayList<>();
MySQLSource mySQLSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, informationDatabase);
mySQLSource.open();
Connection connection = mySQLSource.getConnection();
String sql = "select Surgery_type \"surgeryType\", count(*) \"count\" " +
" from surgery_info " +
" where " +
" Time >= ? and Time <= ? " +
" GROUP BY Surgery_type ";
try {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, startTime);
statement.setString(2, endTime);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Map obj = new HashMap();
obj.put("surgeryType", resultSet.getString("surgeryType"));
obj.put("count", resultSet.getString("count"));
list.add(obj);
}
} catch (SQLException e) {
mySQLSource.close();
throw new RuntimeException(e);
}
mySQLSource.close();
return list;
}
@Override
public List getSurgeryOtherDurationMysql(String startTime, String endTime) {
List<Map> list = new ArrayList<>();
MySQLSource mySQLSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, informationDatabase);
mySQLSource.open();
Connection connection = mySQLSource.getConnection();
String sql = "select date_format( Time,'%Y-%m-%d') \"date\", round(sum(`Aianaesthesia_duration(min)`) / 60, 1) \"aiDuration\", " +
" round(sum(`Doctoranaesthesia_duration(min)`) / 60, 1) \"docDuration\" " +
" from surgery_info " +
" WHERE " +
" Time >= ? and Time <= ? " +
" GROUP BY date_format( Time,'%Y-%m-%d') " +
" ORDER BY date_format( Time,'%Y-%m-%d') ";
try {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, startTime);
statement.setString(2, endTime);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Map map = new HashMap();
map.put("date", resultSet.getString("date"));
map.put("aicount", resultSet.getString("aiDuration"));
map.put("doccount", resultSet.getString("docDuration"));
list.add(map);
}
} catch (SQLException e) {
mySQLSource.close();
throw new RuntimeException(e);
}
mySQLSource.close();
return list;
}
}

View File

@ -1,6 +1,5 @@
package com.rax.vital.timer;
import com.alibaba.fastjson.JSONObject;
import com.rax.common.security.util.SecurityUtils;
import com.rax.vital.datasource.MongoDBSource;
import com.rax.vital.datasource.MySQLSource;
@ -11,12 +10,8 @@ import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
import java.sql.Connection;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@ -45,8 +40,7 @@ public class VitalSignTimer {
private final RevulsionService revulsionService;
// mongoDB定时任务容器
private static final Map<String, TimerTask> timerMongoTaskMap = new ConcurrentHashMap<>() {
};
private static final Map<String, TimerTask> timerMongoTaskMap = new ConcurrentHashMap<>();
// mongoDB链接工具类容器
private static final Map<String, MongoDBSource> mongoDBSourceMap = new ConcurrentHashMap<>();
@ -83,14 +77,6 @@ public class VitalSignTimer {
private static final Map<String, String> masterControlMap = new ConcurrentHashMap<>();
private static final Map<String, WebSocketSession> userSessionMap = new ConcurrentHashMap<>();
private static final Map<String, String> userDatabaseSessionMap = new ConcurrentHashMap<>();
private static final Map<String, WebSocketSession> machineSessionMap = new ConcurrentHashMap<>();
private static final Map<String, String> machineDatabaseSessionMap = new ConcurrentHashMap<>();
/**
* 根据当前用户和患者数据库进行查询生命体征和用药信息并推送数据库类型是MongoDB
*
@ -121,7 +107,7 @@ public class VitalSignTimer {
@Override
public void run() {
MongoTemplate template = finalMongoDBSource.getTemplate();
MongoTemplate template = finalMongoDBSource.getConnection();
HashMap<String, Object> result = new HashMap();
List vitalSignsList = vitalSignsService.getVitalSignsList(template);
result.put("vitalSignsList", vitalSignsList);
@ -236,7 +222,7 @@ public class VitalSignTimer {
mongoDBSource.open();
}
MongoTemplate template = mongoDBSource.getTemplate();
MongoTemplate template = mongoDBSource.getConnection();
aiMedicineService.changeAIFlagMedicine(template, flag, medicine, value);
HashMap<String, Object> result = new HashMap();
@ -253,155 +239,4 @@ public class VitalSignTimer {
}
}
public void createAndSendWSMessageMongo(String database, String username, WebSocketSession session) {
synchronized (username) {
if (!masterControlMap.containsKey(database)) {
masterControlMap.put(database, username);
}
}
String sessionId = session.getId();
TimerTask task = timerMongoTaskMap.get(sessionId);
if (task != null) {
return;
}
MongoDBSource mongoDBSource = mongoDBSourceMap.get(sessionId);
if (mongoDBSource == null) {
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database);
mongoDBSourceMap.put(sessionId, mongoDBSource);
mongoDBSource.open();
}
MongoDBSource finalMongoDBSource = mongoDBSource;
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
MongoTemplate template = finalMongoDBSource.getTemplate();
JSONObject jsonObject = new JSONObject();
List vitalSignsList = vitalSignsService.getVitalSignsList(template);
jsonObject.put("vitalSignsList", vitalSignsList);
List aiMedicineList = aiMedicineService.getAIMedicine(template);
jsonObject.put("aiMedicineList", aiMedicineList);
List docMedicineList = doctorMedicineService.getDocMedicine(template);
jsonObject.put("docMedicineList", docMedicineList);
List revulsionList = revulsionService.getRevulsionServiceList(template);
jsonObject.put("revulsionList", revulsionList);
Map flags = flagService.getFlags(template);
jsonObject.put("flags", flags);
WebSocketMessage message = new TextMessage(jsonObject.toJSONString().getBytes());
try {
session.sendMessage(message);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
// 定时任务设置1秒
Timer timer = new Timer();
timer.schedule(timerTask, 0, 1000);
timerMongoTaskMap.put(sessionId, timerTask);
}
public synchronized void setWSAIFlagSession(WebSocketSession session) {
userSessionMap.put(session.getId(), session);
}
public void removeWSAIFlagSession(WebSocketSession session) {
userSessionMap.remove(session.getId());
if (userDatabaseSessionMap.containsValue(session.getId())) {
for (String database : userDatabaseSessionMap.keySet()) {
if (userDatabaseSessionMap.get(database).equals(session.getId())) {
userDatabaseSessionMap.remove(database);
}
}
}
}
public void changeWSAIFlag(String database, String username, WebSocketSession session, String flag, String medicine, String value) throws IOException {
synchronized (username) {
JSONObject result = new JSONObject();
if (masterControlMap.containsKey(database) && masterControlMap.get(database).equals(username)) {
if (!userDatabaseSessionMap.containsKey(database)) {
userDatabaseSessionMap.put(database, session.getId());
}
if (machineDatabaseSessionMap.containsKey(database)) {
String sessionId = machineDatabaseSessionMap.get(database);
WebSocketSession machineSession = machineSessionMap.get(sessionId);
if (machineSession != null) {
result.put(medicine, value);
result.put("flag", flag);
machineSession.sendMessage(new TextMessage(result.toJSONString().getBytes()));
} else {
result.put("flag", flag);
result.put("msg", "设备端未连接");
result.put("status", 1);
session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
}
} else {
result.put("flag", flag);
result.put("medicine", medicine);
result.put("msg", "设备端未连接");
result.put("status", 1);
session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
}
} else {
result.put("flag", flag);
result.put("medicine", medicine);
result.put("status", 1);
result.put("msg", "不是主控人员");
session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
}
}
}
public synchronized void setMachineSessionMap(WebSocketSession session) throws IOException {
machineSessionMap.put(session.getId(), session);
}
public void removeMachineSessionMap(WebSocketSession session) throws Exception {
machineSessionMap.remove(session.getId());
if (machineDatabaseSessionMap.containsValue(session.getId())) {
for (String database : machineDatabaseSessionMap.keySet()) {
if (machineDatabaseSessionMap.get(database).equals(session.getId())) {
machineDatabaseSessionMap.remove(database);
}
}
}
}
public synchronized void sendMachineFlag(String database, String code, WebSocketSession session) throws IOException {
if (machineDatabaseSessionMap.containsKey(database)) {
if (machineDatabaseSessionMap.get(database).equals(session.getId())) {
sendUserMessage(database, session, code);
} else {
JSONObject msg = new JSONObject();
msg.put("status", 1);
msg.put("msg", "手术已有设备远程中");
session.sendMessage(new TextMessage(msg.toJSONString().getBytes()));
}
} else {
machineDatabaseSessionMap.put(database, session.getId());
sendUserMessage(database, session, code);
}
}
private synchronized void sendUserMessage(String database, WebSocketSession session, String code) throws IOException {
JSONObject result = new JSONObject();
if (userDatabaseSessionMap.containsKey(database)) {
String userSessionId = userDatabaseSessionMap.get(database);
WebSocketSession webSocketSession = userSessionMap.get(userSessionId);
result.put("status", code);
result.put("msg", "");
webSocketSession.sendMessage(new TextMessage(result.toJSONString().getBytes()));
} else {
result.put("status", 1);
result.put("msg", "网站未进行远程");
session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
}
}
}

View File

@ -0,0 +1,321 @@
package com.rax.vital.timer;
import com.alibaba.fastjson.JSONObject;
import com.rax.vital.datasource.CustomDataSource;
import com.rax.vital.datasource.MongoDBSource;
import com.rax.vital.datasource.MySQLSource;
import com.rax.vital.medicine.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
@RefreshScope
@Component
@RequiredArgsConstructor
public class VitalSignTimerWS {
// MongoDB的地址
@Value("${vital-sign.mongodb.host}")
private String mongoDBHost;
// MongoDB的用户名
@Value("${vital-sign.mongodb.username}")
private String mongoUsername;
// MongoDB的用户的密码
@Value("${vital-sign.mongodb.password}")
private String mongoPassword;
// mysql地址
@Value("${vital-sign.mysql.host}")
private String mysqlHost;
// mysql用户名
@Value("${vital-sign.mysql.username}")
private String mysqlUsername;
// mysql用户密码
@Value("${vital-sign.mysql.password}")
private String mysqlPassword;
// 定时任务容器
private static final Map<String, TimerTask> timerTaskMap = new ConcurrentHashMap<>();
// 链接工具类容器
private static final Map<String, CustomDataSource> dataSourceMap = new ConcurrentHashMap<>();
// 主控人员容器
private static final Map<String, String> masterControlMap = new ConcurrentHashMap<>();
// session容器
private static final Map<String, WebSocketSession> userSessionMap = new ConcurrentHashMap<>();
// sessionId容器(数据库名, sessionId)
private static final Map<String, String> userDatabaseSessionMap = new ConcurrentHashMap<>();
// 设备端session容器
private static final Map<String, WebSocketSession> machineSessionMap = new ConcurrentHashMap<>();
// sessionId容器(数据库名, sessionId)
private static final Map<String, String> machineDatabaseSessionMap = new ConcurrentHashMap<>();
private final VitalSignsService vitalSignsService;
private final AIMedicineService aiMedicineService;
private final DoctorMedicineService doctorMedicineService;
private final FlagService flagService;
private final RevulsionService revulsionService;
public void createAndSendWSMessageMongo(String database, String username, WebSocketSession session) {
synchronized (username) {
if (!masterControlMap.containsKey(database)) {
masterControlMap.put(database, username);
}
}
String sessionId = session.getId();
TimerTask task = timerTaskMap.get(sessionId);
if (task != null) {
return;
}
CustomDataSource dataSource = dataSourceMap.get(sessionId);
if (dataSource == null) {
dataSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database);
dataSourceMap.put(sessionId, dataSource);
dataSource.open();
}
CustomDataSource finalMongoDBSource = dataSource;
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
MongoTemplate template = finalMongoDBSource.getConnection();
JSONObject jsonObject = new JSONObject();
List vitalSignsList = vitalSignsService.getVitalSignsList(template);
jsonObject.put("vitalSignsList", vitalSignsList);
List aiMedicineList = aiMedicineService.getAIMedicine(template);
jsonObject.put("aiMedicineList", aiMedicineList);
List docMedicineList = doctorMedicineService.getDocMedicine(template);
jsonObject.put("docMedicineList", docMedicineList);
List revulsionList = revulsionService.getRevulsionServiceList(template);
jsonObject.put("revulsionList", revulsionList);
Map flags = flagService.getFlags(template);
jsonObject.put("flags", flags);
WebSocketMessage message = new TextMessage(jsonObject.toJSONString().getBytes());
try {
session.sendMessage(message);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
// 定时任务设置1秒
Timer timer = new Timer();
timer.schedule(timerTask, 0, 1000);
timerTaskMap.put(sessionId, timerTask);
}
public void createAndSendMessageMySQL(String database, String username, WebSocketSession session) {
synchronized (username) {
if (!masterControlMap.containsKey(database)) {
masterControlMap.put(database, username);
}
}
String sessionId = session.getId();
TimerTask task = timerTaskMap.get(sessionId);
if (task != null) {
return;
}
CustomDataSource dataSource = dataSourceMap.get(sessionId);
if (dataSource == null) {
dataSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, database);
boolean status = dataSource.open();
if (status) {
dataSourceMap.put(database, dataSource);
} else {
JSONObject jsonObject = new JSONObject();
jsonObject.put("status", 1);
jsonObject.put("msg", "数据库未创建, 请重新连接。");
WebSocketMessage message = new TextMessage(jsonObject.toJSONString().getBytes());
try {
session.sendMessage(message);
session.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
CustomDataSource finalDataSource = dataSource;
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
Connection connection = finalDataSource.getConnection();
JSONObject jsonObject = new JSONObject();
List<Map> vitalSignsList = vitalSignsService.getVitalSignsList(connection);
jsonObject.put("vitalSignsList", vitalSignsList);
List<Map> aiMedicineList = aiMedicineService.getAIMedicine(connection);
jsonObject.put("aiMedicineList", aiMedicineList);
List<Map> docMedicineList = doctorMedicineService.getDocMedicine(connection);
jsonObject.put("docMedicineList", docMedicineList);
List revulsionList = revulsionService.getRevulsionServiceList(connection);
jsonObject.put("revulsionList", revulsionList);
Map flags = flagService.getFlag(connection);
jsonObject.put("flags", flags);
WebSocketMessage message = new TextMessage(jsonObject.toJSONString().getBytes());
try {
session.sendMessage(message);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
// 定时任务设置1秒
Timer timer = new Timer();
timer.schedule(timerTask, 0, 1000);
timerTaskMap.put(sessionId, timerTask);
}
public synchronized void setWSAIFlagSession(WebSocketSession session) {
userSessionMap.put(session.getId(), session);
}
public void removeWSAIFlagSession(WebSocketSession session) {
userSessionMap.remove(session.getId());
if (userDatabaseSessionMap.containsValue(session.getId())) {
for (String database : userDatabaseSessionMap.keySet()) {
if (userDatabaseSessionMap.get(database).equals(session.getId())) {
userDatabaseSessionMap.remove(database);
}
}
}
}
public void changeWSAIFlag(String database, String username, WebSocketSession session, String flag, String medicine, String value) throws IOException {
synchronized (username) {
JSONObject result = new JSONObject();
if (masterControlMap.containsKey(database) && masterControlMap.get(database).equals(username)) {
if (!userDatabaseSessionMap.containsKey(database)) {
userDatabaseSessionMap.put(database, session.getId());
}
if (machineDatabaseSessionMap.containsKey(database)) {
String sessionId = machineDatabaseSessionMap.get(database);
WebSocketSession machineSession = machineSessionMap.get(sessionId);
if (machineSession != null) {
result.put(medicine, value);
result.put("flag", flag);
machineSession.sendMessage(new TextMessage(result.toJSONString().getBytes()));
} else {
result.put("flag", flag);
result.put("msg", "设备端未连接");
result.put("status", 1);
session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
}
} else {
result.put("flag", flag);
result.put("medicine", medicine);
result.put("msg", "设备端未连接");
result.put("status", 1);
session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
}
} else {
result.put("flag", flag);
result.put("medicine", medicine);
result.put("status", 1);
result.put("msg", "不是主控人员");
session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
}
}
}
public synchronized void setMachineSessionMap(WebSocketSession session) throws IOException {
machineSessionMap.put(session.getId(), session);
}
public void removeMachineSessionMap(WebSocketSession session) throws Exception {
machineSessionMap.remove(session.getId());
if (machineDatabaseSessionMap.containsValue(session.getId())) {
for (String database : machineDatabaseSessionMap.keySet()) {
if (machineDatabaseSessionMap.get(database).equals(session.getId())) {
machineDatabaseSessionMap.remove(database);
}
}
}
}
public synchronized void sendMachineFlag(String database, String code, WebSocketSession session) throws IOException {
if (machineDatabaseSessionMap.containsKey(database)) {
if (machineDatabaseSessionMap.get(database).equals(session.getId())) {
sendUserMessage(database, session, code);
} else {
JSONObject msg = new JSONObject();
msg.put("status", 1);
msg.put("msg", "手术已有设备远程中");
session.sendMessage(new TextMessage(msg.toJSONString().getBytes()));
}
} else {
machineDatabaseSessionMap.put(database, session.getId());
sendUserMessage(database, session, code);
}
}
private synchronized void sendUserMessage(String database, WebSocketSession session, String code) throws IOException {
JSONObject result = new JSONObject();
if (userDatabaseSessionMap.containsKey(database)) {
String userSessionId = userDatabaseSessionMap.get(database);
WebSocketSession webSocketSession = userSessionMap.get(userSessionId);
result.put("status", code);
result.put("msg", "");
webSocketSession.sendMessage(new TextMessage(result.toJSONString().getBytes()));
} else {
result.put("status", 1);
result.put("msg", "网站未进行远程");
session.sendMessage(new TextMessage(result.toJSONString().getBytes()));
}
}
/**
* 停止指定的某个用户查询的患者数据库定时器数据库类型是MongoDB
*
* @author zhaoyz
*/
public synchronized void stopTimerTask(String simpSessionId) {
TimerTask timerTask = timerTaskMap.get(simpSessionId);
if (timerTask != null) {
timerTask.cancel();
CustomDataSource dataSource = dataSourceMap.get(simpSessionId);
dataSource.close();
timerTaskMap.remove(simpSessionId);
dataSourceMap.remove(simpSessionId);
}
}
}