Compare commits

...

13 Commits

Author SHA1 Message Date
republicline 5e30add660 commit: 2期心跳任务全局封装,语音聊天 2024-11-15 09:38:00 +08:00
republicline 17be499d6d add: 一期代码 2024-11-13 13:48:11 +08:00
republicline 1e39cc83a8 add: 合并一期 2024-11-13 13:48:01 +08:00
republicline 98a33d5649 add: 配合前端修改的折线图. redis, 推送数据为, 每次发生变化的数值(featuretable) 2024-11-13 13:46:59 +08:00
republicline 92550879f8 fix: 聊天室无法推送bug, fix 2024-11-13 13:46:59 +08:00
republicline 793e3e014d fix: 去除聊天室的token校验, 自由使用 2024-11-13 13:46:59 +08:00
republicline 419f9e20d1 fix: 去除聊天室的token校验, 自由使用 2024-11-13 13:46:59 +08:00
republicline e1d59d36e3 fix: 数据库名称采用 a + idNum 2024-11-13 13:46:59 +08:00
republicline 73d3af71aa fix: mysql备份代码 2024-10-15 10:02:14 +08:00
republicline 5243f35dd6 fix: mysql备份代码 2024-10-09 10:14:58 +08:00
republicline 1add5ac60e fix: v2期 2024-10-08 13:10:51 +08:00
republicline ef57152bfb fix: 修复前台注册和后台添加用户的冲突 2024-10-08 13:10:51 +08:00
republicline 14167a0343 fix: v2期 2024-10-08 10:32:08 +08:00
48 changed files with 1319 additions and 553 deletions

View File

@ -2,6 +2,7 @@ package com.rax.auth.endpoint;
import cn.hutool.captcha.CaptchaUtil; import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha; import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.rax.common.core.constant.CacheConstants; import com.rax.common.core.constant.CacheConstants;
import com.rax.common.core.constant.SecurityConstants; import com.rax.common.core.constant.SecurityConstants;
import com.rax.common.security.annotation.Inner; import com.rax.common.security.annotation.Inner;
@ -43,6 +44,7 @@ public class ImageCodeEndpoint {
@SneakyThrows @SneakyThrows
@GetMapping("/image") @GetMapping("/image")
public void image(String randomStr, HttpServletResponse response) { public void image(String randomStr, HttpServletResponse response) {
System.out.println("randomStr = " + randomStr);
ArithmeticCaptcha captcha = new ArithmeticCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT); ArithmeticCaptcha captcha = new ArithmeticCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);
String result = captcha.text(); String result = captcha.text();
@ -55,7 +57,10 @@ public class ImageCodeEndpoint {
@SneakyThrows @SneakyThrows
@GetMapping("/textImage") @GetMapping("/textImage")
public void textImage(String randomStr, HttpServletResponse response) { public void textImage(String randomStr, HttpServletResponse response) {
CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 50); RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
// CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 50);
CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100);
captcha.setGenerator(randomGenerator);
String code = captcha.getCode(); String code = captcha.getCode();
redisTemplate.opsForValue().set(CacheConstants.DEFAULT_CODE_KEY + randomStr, code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS); redisTemplate.opsForValue().set(CacheConstants.DEFAULT_CODE_KEY + randomStr, code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
BufferedImage image = captcha.getImage(); BufferedImage image = captcha.getImage();

View File

@ -8,7 +8,9 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*; import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/** /**
* @author lengleng * @author lengleng
@ -23,11 +25,12 @@ public class RedisTemplateConfiguration {
@Primary @Primary
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.setHashKeySerializer(RedisSerializer.string());
redisTemplate.setValueSerializer(RedisSerializer.java());
redisTemplate.setHashValueSerializer(RedisSerializer.java());
redisTemplate.setConnectionFactory(factory); redisTemplate.setConnectionFactory(factory);
// redisTemplate.setKeySerializer(new StringRedisSerializer());
// redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate; return redisTemplate;
} }

View File

@ -53,7 +53,8 @@ public class UserDTO extends SysUser {
@Override @Override
public String toString() { public String toString() {
return "UserDTO{" + String string = super.toString();
return string + "UserDTO{" +
"userId=" + getUserId() + '\'' + "userId=" + getUserId() + '\'' +
", username='" + getUsername() + '\'' + ", username='" + getUsername() + '\'' +
"role=" + role + "role=" + role +

View File

@ -132,6 +132,11 @@
<groupId>cn.hutool</groupId> <groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId> <artifactId>hutool-core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.14</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -1,6 +1,8 @@
package com.rax.vital.common.util; package com.rax;
import com.rax.vital.common.util.DatabaseNameUtil;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@ -12,13 +14,19 @@ import java.util.Date;
*/ */
public class DBNameTest { public class DBNameTest {
public static void main(String[] args) { public static void main(String[] args) {
String patientName = DatabaseNameUtil.encrypt("eee"); //String patientName = DatabaseNameUtil.encrypt("eee");
String idNum = DatabaseNameUtil.encrypt("10"); //String idNum = DatabaseNameUtil.encrypt("10");
System.out.println("DBName = " + patientName + "_" + idNum); //System.out.println("DBName = " + patientName + "_" + idNum);
//
//
//String date = getDate(new Date(), 10);
//System.out.println("date = " + date);
// AAEb_Qw==_20240812
// decrypt = rtr
// decrypt = 1
String decrypt = DatabaseNameUtil.decrypt("Qw==");
String date = getDate(new Date(), 10); System.out.println("decrypt = " + decrypt);
System.out.println("date = " + date);
} }
public static String getDate(Date now, int days){ public static String getDate(Date now, int days){

View File

@ -16,12 +16,12 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@EnableRaxResourceServer @EnableRaxResourceServer
@EnableScheduling // 开启定时任务 -> 清除日志相关内容 @EnableScheduling // 开启定时任务 -> 清除日志相关内容
// 一期下面解注, 二期注释掉 // 一期下面解注, 二期注释掉
@SpringBootApplication(exclude = MongoAutoConfiguration.class) //@SpringBootApplication(exclude = MongoAutoConfiguration.class)
//@SpringBootApplication @SpringBootApplication
@ComponentScan( @ComponentScan(
basePackages = {"com.rax"}, basePackages = {"com.rax"},
excludeFilters = { excludeFilters = {
@ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.rax.vital.v2.*") @ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.rax.vital.v1.*")
}) })
public class RaxAdminApplication extends SpringBootServletInitializer { public class RaxAdminApplication extends SpringBootServletInitializer {

View File

@ -1,4 +1,4 @@
package com.rax.admin.immu; package com.rax.admin.constants;
/** /**
* project_name:remote-control-backend * project_name:remote-control-backend

View File

@ -35,6 +35,7 @@ public class SysRegisterController {
@SysLog("注册用户") @SysLog("注册用户")
@PostMapping("/user") @PostMapping("/user")
public R<Boolean> registerUser(@RequestBody UserDTO userDto) { public R<Boolean> registerUser(@RequestBody UserDTO userDto) {
System.out.println("reigster-UserDto = " + userDto);
return userService.registerUser(userDto); return userService.registerUser(userDto);
} }

View File

@ -141,6 +141,7 @@ public class SysUserController {
if (!accountMatches) { if (!accountMatches) {
return R.failed("用户名至少2~16位字母或数字区分大小写"); return R.failed("用户名至少2~16位字母或数字区分大小写");
} }
System.out.println("addUser = " + userDto);
return R.ok(userService.saveUser(userDto)); return R.ok(userService.saveUser(userDto));
} }

View File

@ -128,4 +128,11 @@ public interface SysUserService extends IService<SysUser> {
Map getCountByDate(String startTime, String endTime); Map getCountByDate(String startTime, String endTime);
/**
* 此函数用于前台注册用户
* @param userDto
* @return
*/
Boolean regUser(UserDTO userDto);
} }

View File

@ -8,7 +8,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rax.admin.api.dto.HospitalDTO; import com.rax.admin.api.dto.HospitalDTO;
import com.rax.admin.api.entity.SysHospital; import com.rax.admin.api.entity.SysHospital;
import com.rax.admin.immu.RoleRecord; import com.rax.admin.constants.RoleRecord;
import com.rax.admin.mapper.SysHospitalMapper; import com.rax.admin.mapper.SysHospitalMapper;
import com.rax.admin.service.SysHospitalService; import com.rax.admin.service.SysHospitalService;
import com.rax.admin.utils.AuthUtils; import com.rax.admin.utils.AuthUtils;

View File

@ -6,7 +6,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rax.admin.api.dto.SysLogDTO; import com.rax.admin.api.dto.SysLogDTO;
import com.rax.admin.api.entity.SysLog; import com.rax.admin.api.entity.SysLog;
import com.rax.admin.api.entity.SysUser; import com.rax.admin.api.entity.SysUser;
import com.rax.admin.immu.RoleRecord; import com.rax.admin.constants.RoleRecord;
import com.rax.admin.mapper.SysLogMapper; import com.rax.admin.mapper.SysLogMapper;
import com.rax.admin.mapper.SysUserMapper; import com.rax.admin.mapper.SysUserMapper;
import com.rax.admin.service.SysLogService; import com.rax.admin.service.SysLogService;
@ -66,7 +66,7 @@ public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> impleme
.le(SysLog::getCreateTime, lastDayOfMonth) .le(SysLog::getCreateTime, lastDayOfMonth)
.eq(sysLog.getLogType() != null, SysLog::getLogType, sysLog.getLogType()) .eq(sysLog.getLogType() != null, SysLog::getLogType, sysLog.getLogType())
.orderByDesc(SysLog::getCreateTime).list(); .orderByDesc(SysLog::getCreateTime).list();
}else { } else {
list = this.lambdaQuery() list = this.lambdaQuery()
.eq(SysLog::getHospitalId, currentHospital) .eq(SysLog::getHospitalId, currentHospital)
.eq(sysLog.getLogType() != null, SysLog::getLogType, sysLog.getLogType()) .eq(sysLog.getLogType() != null, SysLog::getLogType, sysLog.getLogType())
@ -120,7 +120,11 @@ public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> impleme
userLambdaQueryWrapper.eq(SysUser::getUsername, sysLog.getCreateBy()); userLambdaQueryWrapper.eq(SysUser::getUsername, sysLog.getCreateBy());
SysUser sysUser = sysUserMapper.selectOne(userLambdaQueryWrapper); SysUser sysUser = sysUserMapper.selectOne(userLambdaQueryWrapper);
// 设置到日志对象中 // 设置到日志对象中
sysLog.setHospitalId(sysUser.getHospitalId()); if (sysUser != null) {
sysLog.setHospitalId(sysUser.getHospitalId());
}else {
return Boolean.FALSE;
}
} }
baseMapper.insert(sysLog); baseMapper.insert(sysLog);
return Boolean.TRUE; return Boolean.TRUE;

View File

@ -87,6 +87,7 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
* *
* @param userDto DTO 对象 * @param userDto DTO 对象
* @return success/fail * @return success/fail
* 此保存用于后台添加用户信息.
*/ */
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
@ -137,6 +138,55 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
return Boolean.TRUE; return Boolean.TRUE;
} }
/**
* @param userDto DTO 对象
* @return success/fail
* 此保存用于前台注册用户信息.
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean regUser(UserDTO userDto) {
SysUser sysUser = new SysUser();
BeanUtils.copyProperties(userDto, sysUser);
sysUser.setDelFlag(CommonConstants.STATUS_NORMAL);
sysUser.setCreateBy(userDto.getUsername());
sysUser.setPassword(ENCODER.encode(userDto.getPassword()));
sysUser.setHospitalId(userDto.getHospitalId());
baseMapper.insert(sysUser);
// 保存用户岗位信息
Optional.ofNullable(userDto.getPost()).ifPresent(posts -> {
posts.stream().map(postId -> {
SysUserPost userPost = new SysUserPost();
userPost.setUserId(sysUser.getUserId());
userPost.setPostId(postId);
return userPost;
}).forEach(sysUserPostMapper::insert);
});
// 如果角色为空赋默认角色
if (CollUtil.isEmpty(userDto.getRole())) {
// 获取默认角色编码
String defaultRole = ParamResolver.getStr("USER_DEFAULT_ROLE");
// 默认角色
SysRole sysRole = sysRoleService
.getOne(Wrappers.<SysRole>lambdaQuery().eq(SysRole::getRoleCode, defaultRole));
userDto.setRole(Collections.singletonList(sysRole.getRoleId()));
}
// 插入用户角色关系表
userDto.getRole().stream().map(roleId -> {
SysUserRole userRole = new SysUserRole();
userRole.setUserId(sysUser.getUserId());
userRole.setRoleId(roleId);
return userRole;
}).forEach(sysUserRoleMapper::insert);
return Boolean.TRUE;
}
/** /**
* 通过查用户的全部信息 * 通过查用户的全部信息
* *
@ -448,6 +498,17 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
return R.failed("用户名至少2~16位字母或数字区分大小写"); return R.failed("用户名至少2~16位字母或数字区分大小写");
} }
if (userDto.getHospitalId() == null) {
return R.failed("请选择医院");
}
// 查询所有医院ID
List<Long> hospitalIdList = sysHospitalService.list()
.stream()
.map(SysHospital::getId).toList();
if (!hospitalIdList.contains(userDto.getHospitalId())) {
return R.failed("医院不存在");
}
// 判断用户名是否存在 // 判断用户名是否存在
SysUser sysUser = this.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, userDto.getUsername())); SysUser sysUser = this.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, userDto.getUsername()));
@ -455,7 +516,7 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
String message = MsgUtils.getMessage(ErrorCodes.SYS_USER_USERNAME_EXISTING, userDto.getUsername()); String message = MsgUtils.getMessage(ErrorCodes.SYS_USER_USERNAME_EXISTING, userDto.getUsername());
return R.failed(message); return R.failed(message);
} }
return R.ok(saveUser(userDto)); return R.ok(regUser(userDto));
} }
/** /**

View File

@ -23,7 +23,6 @@ import java.util.List;
*/ */
@Slf4j @Slf4j
@Component @Component
@Service
public class LogTimerTask { public class LogTimerTask {
@Autowired @Autowired

View File

@ -0,0 +1,31 @@
package com.rax.admin.timmer;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.stereotype.Component;
/**
* @project_name: rax-remote-v2
* @time: 2024/10/8 10:57
* @author: republicline
* @description: mongoDB定时备份
*/
@Slf4j
@Component
public class MongoTimer {
//String connectionString = "mongodb://localhost:27017";
//MongoClient mongoClient = MongoClients.create(connectionString);
//
//
//
//public void backup() {
// MongoIterable<String> DbNames = mongoClient.listDatabaseNames();
// for (String dbName : DbNames) {
//
// }
//}
}

View File

@ -0,0 +1,132 @@
package com.rax.admin.timmer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.File;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* @project_name: rax-remote-v2
* @time: 2024/10/8 10:57
* @author: republicline
* @description: mysql定时备份
*/
@Component
@Slf4j
public class MySqlTimer {
public static void main(String[] args) throws Exception {
backup();
}
@Scheduled(cron = "0 0 0 * * 0")
public static void backup() throws Exception {
String connectionUrl = "jdbc:mysql://110.41.142.124:3306";
String ip = "110.41.142.124";
String port = "3306";
String username = "root";
String password = "Xg137839";
Connection connection = DriverManager.getConnection(connectionUrl, username, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SHOW DATABASES");
// System.out.println("MySQL服务器上的数据库列表:");
while (resultSet.next()) {
String databaseName = resultSet.getString(1);
System.out.println(databaseName);
if ("sys".equals(databaseName)) {
continue;
}
dbBackUpMysql(
ip,
port,
username,
password,
"/RuiAx/mysql_backup",
databaseName);
}
resultSet.close();
statement.close();
connection.close();
}
/**
* 备份mysql数据库
*
* @param username 账号
* @param pwd 密码
* @param ip 地址
* @param port 端口
* @param path 路径
* @param dbName 数据库名
* @throws Exception
*/
public static void dbBackUpMysql(String ip, String port, String username, String pwd, String path, String dbName) throws Exception {
//mysqldump -uroot -pldeSpQEL0Pbz5A61dCNb --host=123.56.234.243 --port=3309 edc > /opt/2024-10-08/edc.sql
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String time = simpleDateFormat.format(new Date());
path = path + File.separator + time + File.separator;
String pathSql = path + dbName + ".sql";
File filePath = new File(path);
File fileSql = new File(pathSql);
//创建备份sql文件
if (!filePath.exists()) {
filePath.mkdirs();
}
if (!fileSql.exists()) {
fileSql.createNewFile();
}
//mysqldump -uroot -pldeSpQEL0Pbz5A61dCNb --host=123.56.234.243 --port=3309 edc > /opt/2024-10-08/edc.sql
StringBuffer sb = new StringBuffer();
sb.append("mysqldump");
sb.append(" -u" + username);
sb.append(" -p" + pwd);
sb.append(" --host=" + ip);
sb.append(" --port=" + port);
sb.append(" " + dbName + " >");
sb.append(pathSql);
System.out.println("cmd命令为" + sb.toString());
System.out.println("开始备份:" + dbName);
Process process = null;
//判断操作系统 windwos与linux使用的语句不一样
if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
process = Runtime.getRuntime().exec("cmd /c" + sb);
} else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
process = Runtime.getRuntime().exec("/bin/sh -c" + sb);
} else {
log.error("暂不支持该操作系统,进行数据库备份或还原!");
throw new Exception("暂不支持该操作系统,进行数据库备份或还原!");
}
//设置超时五分钟
process.waitFor(300, TimeUnit.SECONDS);
//输出返回的错误信息
// StringBuffer mes = new StringBuffer();
// String tmp = "";
// BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// while ((tmp = error.readLine()) != null) {
// mes.append(tmp + "\n");
// }
// if (mes != null || !"".equals(mes)) {
// System.out.println("备份成功!==>" + mes);
// }
// error.close();
}
}

View File

@ -1,7 +1,7 @@
package com.rax.admin.utils; package com.rax.admin.utils;
import cn.hutool.core.convert.Convert; import cn.hutool.core.convert.Convert;
import com.rax.admin.immu.RoleRecord; import com.rax.admin.constants.RoleRecord;
import com.rax.common.core.constant.CacheConstants; import com.rax.common.core.constant.CacheConstants;
import com.rax.common.core.util.RedisUtils; import com.rax.common.core.util.RedisUtils;
import com.rax.common.security.service.RaxUser; import com.rax.common.security.service.RaxUser;

View File

@ -0,0 +1,58 @@
package com.rax.admin.utils;
import java.sql.*;
import java.util.ResourceBundle;
/**
* 适应mysql不同数据源
*
* @author republicline
*/
public class JDBCUtil {
private static final String driverClassName = "com.mysql.jdbc.Driver";
private static final String username = "root";
private static final String password = "Xg137839";
private static final String url = "jdbc:mysql://110.41.142.124:3306/";
private JDBCUtil() {
}
//注册驱动
static {
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
//jdbc工具类,获取连接
public static Connection getConnection(String databaseName) throws Exception {
return DriverManager.getConnection(
url + databaseName,
username,
password);
}
//jdbc工具类,关闭连接
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,46 @@
//package com.rax.vital.common.datasource;
//
//
//import com.zaxxer.hikari.HikariConfig;
//import com.zaxxer.hikari.HikariDataSource;
//
//import java.sql.Connection;
//import java.sql.SQLException;
//
//public class DynamicDataSource {
//
// private HikariDataSource dataSource;
//
// // 动态创建连接池
// public void createDataSource(String databaseName) {
// HikariConfig config = new HikariConfig();
//
// config.setDriverClassName("com.mysql.cj.jdbc.Driver");
// config.setJdbcUrl("jdbc:mysql://110.41.142.124:3306/" + databaseName + "?useUnicode=true&characterEncoding=utf-8&useSSL=false");
// config.setUsername("root");
// config.setPassword("Xg137839");
//
// // 配置连接池参数
// config.setMinimumIdle(1);
// config.setMaximumPoolSize(5);
// config.setIdleTimeout(1000 * 60 * 3); // 空闲超时时间
// config.setConnectionTimeout(1000 * 60 * 3); // 连接超时时间
// config.setMaxLifetime(1000 * 60 * 3); // 最大连接寿命
// this.dataSource = new HikariDataSource(config);
// }
//
// // 获取连接
// public Connection getConnection() throws SQLException {
// if (dataSource == null) {
// throw new IllegalStateException("DataSource is not initialized. Call createDataSource() first.");
// }
// return dataSource.getConnection();
// }
//
// // 关闭数据源
// public void closeDataSource() {
// if (dataSource != null) {
// dataSource.close();
// }
// }
//}

View File

@ -22,10 +22,14 @@ public class MongoDBSource extends CustomDataSource {
private SimpleMongoClientDatabaseFactory simpleMongoClientDatabaseFactory; private SimpleMongoClientDatabaseFactory simpleMongoClientDatabaseFactory;
public MongoDBSource(String host, String password, String username, String database) { private static final String MONGO_CONNECTION_URL =
this.host = host; "mongodb://useradmin:Xg137839mg@110.41.142.124:27017/?directConnection=true";
this.password = password;
this.username = username;
public MongoDBSource(String database) {
this.host = "110.41.142.124:27017";
this.password = "Xg137839mg";
this.username = "useradmin";
this.database = database; this.database = database;
} }

View File

@ -35,12 +35,12 @@ public class MySQLSource extends CustomDataSource {
this.database = database; this.database = database;
} }
@SneakyThrows
public boolean open() { public boolean open() {
boolean status = true; boolean status = true;
try { try {
dataSource = new DruidDataSource(); dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://" + this.host + "/" + this.database); dataSource.setUrl("jdbc:mysql://" + this.host + "/" + this.database +"?allowPublicKeyRetrieval=true");
dataSource.setDriverClassName(driver); dataSource.setDriverClassName(driver);
dataSource.setUsername(this.username); dataSource.setUsername(this.username);
dataSource.setPassword(this.password); dataSource.setPassword(this.password);

View File

@ -34,8 +34,7 @@ public class SysLoggerBuilder {
String uri = session.getUri() != null ? session.getUri().toString() : "unknown"; String uri = session.getUri() != null ? session.getUri().toString() : "unknown";
String userAgent = session.getHandshakeHeaders().getFirst("User-Agent") != null ? String userAgent = session.getHandshakeHeaders().getFirst("User-Agent") != null ?
session.getHandshakeHeaders().getFirst("User-Agent") : "unknown"; session.getHandshakeHeaders().getFirst("User-Agent") : "unknown";
String params = session.getUri() != null ? String params = session.getUri() != null ? session.getUri().getQuery() : "unknown";
session.getUri().getQuery() : "unknown";
// 解析token // 解析token
Map<String, Object> stringObjectMap = tokenUtil.parseToken(token); Map<String, Object> stringObjectMap = tokenUtil.parseToken(token);

View File

@ -12,10 +12,10 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* project_name: remote-control-backend * @project_name: remote-control-backend
* time: 2024/9/4 14:56 * @time: 2024/9/4 14:56
* author: republicline * @author: republicline
* description: * @description:
*/ */
@Component @Component
public class TokenUtil { public class TokenUtil {

View File

@ -0,0 +1,130 @@
//package com.rax.vital.controller;
//
//import com.rax.common.core.util.R;
//import com.rax.common.security.annotation.Inner;
//import com.rax.vital.common.datasource.DynamicDataSource;
//import com.rax.vital.entity.VisualBody;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//import java.sql.Connection;
//import java.sql.PreparedStatement;
//import java.sql.SQLException;
//import java.util.concurrent.*;
//
///**
// * @project_name: rax-remote-v2
// * @time: 2024/11/5 11:05
// * @author: republicline
// * @description: 仪器端和服务端通信接口
// */
//@RestController
//@RequestMapping("/machine")
//public class MachineController {
//
// // 生命体征表名
// private static final String FEATURE_TABLE_NAME = "featuretable";
//
// // 异步入库
// private ExecutorService executorService = Executors.newFixedThreadPool(5);
//
// // 动态数据源
// private ConcurrentHashMap<String, DynamicDataSource> dynamicDataSources = new ConcurrentHashMap<>();
//
// // 仪器端生命体征数据入库
// @PostMapping("/save")
// @Inner(value = false)
// public R<Object> saveVitalBodyData(VisualBody visualBody) {
// System.out.println("visualBody = " + visualBody);
//
// for (String key : dynamicDataSources.keySet()) System.out.println("key = " + key);
//
// // 校验
// if (visualBody == null) return R.failed("参数不能为空");
//
// if (visualBody.getDatabaseName() == null ||
// visualBody.getPhase() == null || visualBody.getBIS() == null ||
// visualBody.getHR() == null || visualBody.getSBP() == null ||
// visualBody.getDBP() == null || visualBody.getST() == null ||
// visualBody.getTEMP() == null || visualBody.getSP02() == null ||
// visualBody.getEtCO2() == null || visualBody.getPPG() == null ||
// visualBody.getABG() == null || visualBody.getTOF() == null ||
// visualBody.getTIME() == null) {
// return R.failed("参数含有空值");
// }
// saveVitalBodyDataAsync(visualBody);
// return R.ok("success");
// }
//
// // 关闭数据源
// @PostMapping("/close")
// @Inner(value = false)
// public R<Object> closeDataSource(String databaseName) {
// if (databaseName == null) {
// return R.failed("参数不能为空");
// }
// dynamicDataSources.remove(databaseName);
// DynamicDataSource dynamicDataSource = dynamicDataSources.get(databaseName);
// if (dynamicDataSource == null) {
// return R.failed("数据源不存在");
// }
// dynamicDataSource.closeDataSource();
// return R.ok("success");
// }
//
// private void saveVitalBodyDataAsync(VisualBody visualBody) {
// executorService.execute(() -> {
// try {
//
// String databaseName = visualBody.getDatabaseName();
// if (!dynamicDataSources.containsKey(databaseName)) {
// // 创建动态数据源
// System.out.println("连接池创建数据源");
// DynamicDataSource dynamicDataSource = new DynamicDataSource();
// dynamicDataSource.createDataSource(databaseName);
// dynamicDataSources.put(databaseName, dynamicDataSource);
// }
//
// if (dynamicDataSources.get(databaseName) == null) {
// dynamicDataSources.remove(databaseName);
// throw new RuntimeException("数据源不存在");
// }
//
// // 获取连接
// Connection connection = dynamicDataSources.get(databaseName).getConnection();
//
// if (connection == null) {
// throw new RuntimeException("数据库连接失败");
// }
//
// // 数据库操作
// String sql = String.format("""
// INSERT INTO %s
// (Phase, BIS, HR, SBP, DBP, ST, TEMP, SPO2, EtCO2, PPG, ABG, TOF, `TIME`)
// VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?);
// """, FEATURE_TABLE_NAME);
// PreparedStatement ps = connection.prepareStatement(sql);
// ps.setInt(1, visualBody.getPhase());
// ps.setDouble(2, visualBody.getBIS());
// ps.setDouble(3, visualBody.getHR());
// ps.setDouble(4, visualBody.getSBP());
// ps.setDouble(5, visualBody.getDBP());
// ps.setDouble(6, visualBody.getST());
// ps.setDouble(7, visualBody.getTEMP());
// ps.setDouble(8, visualBody.getSP02());
// ps.setDouble(9, visualBody.getEtCO2());
// ps.setDouble(10, visualBody.getPPG());
// ps.setDouble(11, visualBody.getABG());
// ps.setDouble(12, visualBody.getTOF());
// ps.setTimestamp(13, visualBody.getTIME());
// ps.execute();
// } catch (SQLException e) {
// throw new RuntimeException(e);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
//
// });
// }
//}

View File

@ -0,0 +1,162 @@
package com.rax.vital.entity;
import java.sql.Timestamp;
/**
* @project_name: rax-remote-v2
* @time: 2024/11/5 11:10
* @author: republicline
* @description: 生命体征实体类
*/
public class VisualBody {
private String databaseName;
private Integer Phase;
private Double BIS;
private Double HR;
private Double SBP;
private Double DBP;
private Double ST;
private Double TEMP;
private Double SP02;
private Double EtCO2;
private Double PPG;
private Double ABG;
private Double TOF;
private Timestamp TIME;
public String getDatabaseName() {
return databaseName;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public Integer getPhase() {
return Phase;
}
public void setPhase(Integer phase) {
Phase = phase;
}
public Double getBIS() {
return BIS;
}
public void setBIS(Double BIS) {
this.BIS = BIS;
}
public Double getHR() {
return HR;
}
public void setHR(Double HR) {
this.HR = HR;
}
public Double getSBP() {
return SBP;
}
public void setSBP(Double SBP) {
this.SBP = SBP;
}
public Double getST() {
return ST;
}
public void setST(Double ST) {
this.ST = ST;
}
public Double getTEMP() {
return TEMP;
}
public void setTEMP(Double TEMP) {
this.TEMP = TEMP;
}
public Double getSP02() {
return SP02;
}
public void setSP02(Double SP02) {
this.SP02 = SP02;
}
public Double getEtCO2() {
return EtCO2;
}
public void setEtCO2(Double etCO2) {
EtCO2 = etCO2;
}
public Double getPPG() {
return PPG;
}
public void setPPG(Double PPG) {
this.PPG = PPG;
}
public Double getABG() {
return ABG;
}
public void setABG(Double ABG) {
this.ABG = ABG;
}
public Double getTOF() {
return TOF;
}
public void setTOF(Double TOF) {
this.TOF = TOF;
}
public Timestamp getTIME() {
return TIME;
}
public void setTIME(Timestamp TIME) {
this.TIME = TIME;
}
public Double getDBP() {
return DBP;
}
public void setDBP(Double DBP) {
this.DBP = DBP;
}
@Override
public String toString() {
return "VisualBody{" +
"databaseName='" + databaseName + '\'' +
", Phase=" + Phase +
", BIS=" + BIS +
", DBP=" + DBP +
", HR=" + HR +
", SBP=" + SBP +
", ST=" + ST +
", TEMP=" + TEMP +
", SP02=" + SP02 +
", EtCO2=" + EtCO2 +
", PPG=" + PPG +
", ABG=" + ABG +
", TOF=" + TOF +
", TIME=" + TIME +
'}';
}
}

View File

@ -9,6 +9,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor; import org.springframework.web.socket.server.HandshakeInterceptor;
@ -22,10 +23,10 @@ public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(medicineHandler(), "/rax/vitalSignsMedicine") registry.addHandler(medicineHandler(), "/rax/vitalSignsMedicine")
.addHandler(chatHandler(), "/rax/chatRoom") .addHandler(chatHandler(), "/rax/chatRoom")
.addHandler(addMedicineHandler(), "/rax/addMedicine") // .addHandler(addMedicineHandler(), "/rax/addMedicine")
.addHandler(machineFeedbackHandler(),"/rax/getMedicine") // .addHandler(machineFeedbackHandler(),"/rax/getMedicine")
.addInterceptors(new HttpSessionHandshakeInterceptor()) // .addInterceptors(new HttpSessionHandshakeInterceptor())
.addInterceptors(webSocketInterceptors()) // .addInterceptors(webSocketInterceptors())
.setAllowedOrigins("*"); .setAllowedOrigins("*");
} }
@ -39,15 +40,15 @@ public class WebSocketConfig implements WebSocketConfigurer {
return new ChatHandler(); return new ChatHandler();
} }
@Bean // @Bean
public WebSocketHandler addMedicineHandler() { // public WebSocketHandler addMedicineHandler() {
return new AddMedicineHandler(); // return new AddMedicineHandler();
} // }
@Bean // @Bean
public WebSocketHandler machineFeedbackHandler() { // public WebSocketHandler machineFeedbackHandler() {
return new MachineFeedbackHandler(); // return new MachineFeedbackHandler();
} // }
@Bean @Bean
public HandshakeInterceptor webSocketInterceptors() { public HandshakeInterceptor webSocketInterceptors() {

View File

@ -36,7 +36,6 @@ public class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {
/** /**
* stomp未登录验证 * stomp未登录验证
*
* @param registration * @param registration
*/ */
@Override @Override

View File

@ -1,20 +1,29 @@
package com.rax.vital.v1.handler; package com.rax.vital.v1.handler;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.vital.common.datasource.CustomDataSource;
import com.rax.vital.common.datasource.MySQLSource;
import com.rax.vital.common.util.GetHttpParamUtil; import com.rax.vital.common.util.GetHttpParamUtil;
import com.rax.vital.v1.medicine.service.ChatService; import com.rax.vital.v1.medicine.service.ChatService;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType; import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.*; import org.springframework.web.socket.*;
import java.io.IOException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ChatHandler implements WebSocketHandler { public class ChatHandler implements WebSocketHandler {
@Resource @Resource
@ -23,8 +32,31 @@ public class ChatHandler implements WebSocketHandler {
@Resource @Resource
private ChatService chatService; private ChatService chatService;
@Autowired
private RedisTemplate redisTemplate;
// 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 ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(5);
private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap(); private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap();
// dbName -> sessionList
private Map<String, List<WebSocketSession>> dbNameSessionList = new ConcurrentHashMap();
// sessionId -> dbName
private Map<String, String> sessionDbMap = new ConcurrentHashMap();
@Override @Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception { public void afterConnectionEstablished(WebSocketSession session) throws Exception {
startHeartbeat(session); startHeartbeat(session);
@ -32,7 +64,8 @@ public class ChatHandler implements WebSocketHandler {
@Override @Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
String decode = URLDecoder.decode(session.getUri().getQuery()); String query = session.getUri().getQuery();
String decode = URLDecoder.decode(query);
Map params = GetHttpParamUtil.getParams(decode); Map params = GetHttpParamUtil.getParams(decode);
String token = (String) params.get("token"); String token = (String) params.get("token");
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
@ -41,30 +74,89 @@ public class ChatHandler implements WebSocketHandler {
String payload = (String) message.getPayload(); String payload = (String) message.getPayload();
JSONObject jsonObject = JSONObject.parseObject(payload); JSONObject jsonObject = JSONObject.parseObject(payload);
if ("heartbeat".equals(jsonObject.getString("msgType"))) { if ("heartbeat".equals(jsonObject.getString("msgType"))) {
// session.sendMessage(new TextMessage("")); // session.sendMessage(new TextMessage(""));
} else { } else if ("init".equals(jsonObject.getString("msgType"))) {
String patientName = jsonObject.getString("patientName"); // 初始化, 将session信息保存起来
String idNum = jsonObject.getString("idNum"); String dbName = 'a' + jsonObject.getString("idNum");
String date = jsonObject.getString("date"); // if (RedisUtils.hasKey("chat_" + dbName)) {
// List<WebSocketSession> sessionList = RedisUtils.get("chat_" + dbName);
//
// dbNameSessionList.put(dbName, sessionList);
// HashMap<String, String> map = new HashMap<>();
// map = RedisUtils.get("chat_sessionId_" + dbName);
// sessionDbMap.putAll(map);
// return;
// }
if (!dbNameSessionList.containsKey(dbName)) {
ArrayList<WebSocketSession> sessionArrayList = new ArrayList<>();
dbNameSessionList.put(dbName, sessionArrayList);
sessionDbMap.put(session.getId(), dbName);
}
List<WebSocketSession> webSocketSessions = dbNameSessionList.get(dbName);
webSocketSessions.add(session);
// 创建数据库表
initTChatTable(dbName, session);
// ArrayList<String> sessionIDList = new ArrayList<>();
// for (WebSocketSession webSocketSession : webSocketSessions) {
// if (webSocketSession.isOpen()) {
// String id = session.getId();
// sessionIDList.add(id);
// }
// }
//
// // 保存到redis
// redisTemplate.opsForValue().set("chat_" + dbName, sessionIDList);
// redisTemplate.expire("chat_" + dbName, 60 * 60, TimeUnit.SECONDS);
// redisTemplate.opsForHash().putAll("chat_sessionId_" + dbName, sessionDbMap);
// redisTemplate.expire("chat_" + dbName, 60 * 60, TimeUnit.SECONDS);
} else if ("msg".equals(jsonObject.getString("msgType")) ||
"audio".equals(jsonObject.getString("msgType"))) {
//String patientName = jsonObject.getString("patientName");
String dbName = 'a' + jsonObject.getString("idNum");
//String date = jsonObject.getString("date");
String msgType = jsonObject.getString("msgType");
// 消息内容 // 消息内容
String msg = jsonObject.getString("msg"); String content = jsonObject.getString("msg");
chatService.sendMessageMysql(username, patientName, idNum, date, session, msg); List<WebSocketSession> webSocketSessions = dbNameSessionList.get(dbName);
// 转发消息
JSONObject param = new JSONObject();
param.put("msgType", msgType);
param.put("createUser", username);
param.put("createTime", DateUtil.now());
param.put("msg", content);
param.put("dbName", dbName);
for (WebSocketSession webSocketSession : webSocketSessions) {
webSocketSession.sendMessage(new TextMessage(param.toJSONString().getBytes()));
}
// 异步入库
EXECUTOR_SERVICE.execute(() -> saveChatMsg(param.toJSONString()));
// 之前的
// chatService.sendMessageMysql(username, patientName, dbName, msgType, session, msg, webSocketSessions);
} }
} else {
String msgContent = "token无效,认证失败";
JSONObject msg = new JSONObject();
msg.put("msgType", "msg");
msg.put("msg", msgContent);
session.sendMessage(new TextMessage(msg.toJSONString().getBytes()));
} }
} }
@Override @Override
public void handleTransportError(WebSocketSession session, Throwable exception) { public void handleTransportError(WebSocketSession session, Throwable exception) {
System.out.println("Error: " + exception.getMessage()); System.out.println("Error: " + exception.getMessage());
stopMap(session);
} }
@Override @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
System.out.println("CloseStatus: " + closeStatus.getReason() + closeStatus.getCode()); System.out.println("CloseStatus: " + closeStatus.getReason() + closeStatus.getCode());
stopHeartbeat(session); stopHeartbeat(session);
chatService.stopTask(session.getId()); //chatService.stopTask(session.getId());
stopMap(session);
} }
@Override @Override
@ -83,7 +175,7 @@ public class ChatHandler implements WebSocketHandler {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes())); session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else { } else {
stopHeartbeat(session); stopHeartbeat(session);
chatService.stopTask(session.getId()); //chatService.stopTask(session.getId());
session.close(); session.close();
} }
} catch (Exception e) { } catch (Exception e) {
@ -100,4 +192,117 @@ public class ChatHandler implements WebSocketHandler {
heartbeatExecutor.shutdownNow(); heartbeatExecutor.shutdownNow();
} }
private void stopMap(WebSocketSession session) {
String dbName = sessionDbMap.get(session.getId());
if (dbName != null) {
dbNameSessionList.remove(dbName);
}
sessionDbMap.remove(session.getId());
}
// 初始化聊天表格
private void initTChatTable(String dbName, WebSocketSession session) {
try {
CustomDataSource source = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, dbName);
source.open();
Connection connection = source.getConnection();
if (connection != null) {
String tableName = "t_chat";
Statement statement = connection.createStatement();
// 检查表是否存在的 SQL 语句
String checkTableSQL = "SELECT COUNT(*) FROM information_schema.tables " +
"WHERE table_schema = DATABASE() AND table_name = '" + tableName + "';";
ResultSet resultSet = statement.executeQuery(checkTableSQL);
if (resultSet.next() && resultSet.getInt(1) == 0) { // 表不存在
// 表不存在执行创建操作
String createTableSQL = """
CREATE TABLE %s (
`id` int NOT NULL AUTO_INCREMENT,
`content` longblob,
`create_time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`create_user` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`msg_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`deleted` bit(1) NULL DEFAULT NULL,
`revoked` bit(1) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
""".formatted(tableName);
statement.execute(createTableSQL);
}
source.close();
} else {
source.close();
JSONObject jsonObject = new JSONObject();
jsonObject.put("status", 1);
jsonObject.put("msg", "数据库未创建, 请重新连接");
jsonObject.put("msgType", "msg");
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
}
} catch (SQLException | IOException e) {
throw new RuntimeException(e);
}
// 创建数据库,查询历史
// DatabaseMetaData metaData = connection.getMetaData();
// ResultSet tablesx = metaData.getTables(null, null, tableName, new String[]{"TABLE"});
// String sql = "select content, create_time \"creatTime\", create_user \"createUser\", create_name \"createName\" from t_chat where deleted = 0 and revoked = 0 order by create_time asc ";
// if (tablesx.next()) {
//
// Statement statement = connection.createStatement();
// ResultSet resultSet = statement.executeQuery(sql);
// while (resultSet.next()) {
// Map map = new HashMap();
// map.put("content", resultSet.getString("content"));
// map.put("creatTime", resultSet.getString("creatTime"));
// map.put("createUser", resultSet.getString("createUser"));
// map.put("createName", resultSet.getString("createName"));
// history.add(map);
// }
// JSONObject param = new JSONObject();
// param.put("history", history);
// param.put("msgType", "msg");
//// session.sendMessage(new TextMessage(param.toJSONString().getBytes()));
// for (WebSocketSession webSocketSession : webSocketSessionList) {
// webSocketSession.sendMessage(new TextMessage(param.toJSONString().getBytes()));
// }
// }
}
// 保存聊天消息到数据库
private void saveChatMsg(String jsonStr) {
// 发消息, 入库
if (StringUtils.hasText(jsonStr)) {
JSONObject jsonObj = JSON.parseObject(jsonStr);
String msgType = jsonObj.getString("msgType");
Object content = jsonObj.get("content");
String username = jsonObj.getString("createUser");
String dbName = jsonObj.getString("dbName");
String now = DateUtil.now();
MySQLSource source = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, dbName);
source.open();
Connection connection = source.getConnection();
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement("INSERT INTO t_chat (content, create_time, create_user, msg_type, deleted, revoked) VALUES (?, ?, ?, ?, ?, ?)");
preparedStatement.setObject(1, content);
preparedStatement.setString(2, now);
preparedStatement.setString(3, username);
preparedStatement.setString(4, msgType);
preparedStatement.setInt(5, 0);
preparedStatement.setInt(6, 0);
preparedStatement.execute();
} catch (SQLException e) {
source.close();
e.printStackTrace();
}
source.close();
}
}
} }

View File

@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONObject;
import com.rax.vital.common.util.GetHttpParamUtil; import com.rax.vital.common.util.GetHttpParamUtil;
import com.rax.vital.v1.timer.VitalSignTimerWS; import com.rax.vital.v1.timer.VitalSignTimerWS;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType; import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
@ -12,9 +13,6 @@ import org.springframework.web.socket.*;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MedicineHandler implements WebSocketHandler { public class MedicineHandler implements WebSocketHandler {
@ -24,11 +22,13 @@ public class MedicineHandler implements WebSocketHandler {
@Resource @Resource
private OAuth2AuthorizationService authorizationService; private OAuth2AuthorizationService authorizationService;
private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap(); private Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap();
@Override @Override
public void afterConnectionEstablished(WebSocketSession session) { public void afterConnectionEstablished(WebSocketSession session) {
startHeartbeat(session); sessionMap.put(session.getId(), session);
} }
@Override @Override
@ -45,23 +45,24 @@ public class MedicineHandler implements WebSocketHandler {
if ("heartbeat".equals(jsonObject.getString("msgType"))) { if ("heartbeat".equals(jsonObject.getString("msgType"))) {
// session.sendMessage(new TextMessage("")); // session.sendMessage(new TextMessage(""));
} else { } else {
String patientName = jsonObject.getString("patientName"); // String patientName = jsonObject.getString("patientName");
String idNum = jsonObject.getString("idNum"); String idNum = jsonObject.getString("idNum");
String databaseName = idNum; String databaseName = 'a' + idNum;
vitalSignTimerWS.createAndSendMessageMySQL(databaseName, username, session); vitalSignTimerWS.createAndSendMessageMySQL(databaseName, username, session);
} }
} }
@Override @Override
public void handleTransportError(WebSocketSession session, Throwable exception) { public void handleTransportError(WebSocketSession session, Throwable exception) {
sessionMap.remove(session.getId());
System.out.println("Error: " + exception.getMessage()); System.out.println("Error: " + exception.getMessage());
} }
@Override @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
System.out.println("MedicineHandler Connection closed:" + closeStatus.getReason()); System.out.println("MedicineHandler Connection closed:" + closeStatus.getReason());
stopHeartbeat(session); // stopHeartbeat(session);
vitalSignTimerWS.stopTimerTask(session.getId()); sessionMap.remove(session.getId());
} }
@Override @Override
@ -69,32 +70,24 @@ public class MedicineHandler implements WebSocketHandler {
return false; return false;
} }
private void startHeartbeat(WebSocketSession session) {
if (!timerTaskMap.containsKey(session.getId())) {
ScheduledExecutorService heartbeatExecutor = Executors.newScheduledThreadPool(1); @Scheduled(fixedRate = 30000)
heartbeatExecutor.scheduleAtFixedRate(() -> { private void sendHeartbeat() {
for (WebSocketSession session : sessionMap.values()) {
if (session.isOpen()) {
try { try {
if (session.isOpen()) { JSONObject jsonObject = new JSONObject();
JSONObject jsonObject = new JSONObject(); jsonObject.put("msgType", "heartbeat");
jsonObject.put("msgType", "heartbeat"); session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else {
session.close();
stopHeartbeat(session);
vitalSignTimerWS.stopTimerTask(session.getId());
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
stopHeartbeat(session);
} }
}, 0, 10, TimeUnit.SECONDS); }else {
timerTaskMap.put(session.getId(), heartbeatExecutor); sessionMap.remove(session.getId());
vitalSignTimerWS.stopTimerTask(session.getId());
}
} }
} }
private void stopHeartbeat(WebSocketSession session) {
ScheduledExecutorService heartbeatExecutor = timerTaskMap.get(session.getId());
heartbeatExecutor.shutdownNow();
}
} }

View File

@ -41,7 +41,7 @@ public class ChatController {
String date = params.getString("date"); String date = params.getString("date");
// 消息内容 // 消息内容
String msg = params.getString("msg"); String msg = params.getString("msg");
chatService.sendMessage(username, patientName, idNum, date, simpSessionId, msg); //chatService.sendMessage(username, patientName, idNum, date, simpSessionId, msg);
} else { } else {
throw new AccessDeniedException("Access is denied"); throw new AccessDeniedException("Access is denied");
} }

View File

@ -96,7 +96,7 @@ public class MedicineController {
@PostMapping("/getPatientInfoM") @PostMapping("/getPatientInfoM")
public R getPatientInfoM(String patientName, String idNum, String date) { public R getPatientInfoM(String patientName, String idNum, String date) {
String databaseName = patientName + idNum; String databaseName = 'a' + idNum;
return vitalSignsService.getPatientInfoM(databaseName); return vitalSignsService.getPatientInfoM(databaseName);
} }

View File

@ -3,15 +3,11 @@ package com.rax.vital.v1.medicine.service;
import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.WebSocketSession;
import java.io.IOException; import java.io.IOException;
import java.util.List;
public interface ChatService { public interface ChatService {
void sendMessage(String username, String patientName, String idNum, String date, String simpSessionId, String msg);
void sendMessage(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) throws IOException; void sendMessageMysql(String username, String patientName, String idNum, String msgType, WebSocketSession session, String msg, List<WebSocketSession> webSocketSessions) throws Exception;
void sendMessageMysql(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) throws Exception;
void stopTimerTask(String simpSessionId);
void stopTask(String simpSessionId); void stopTask(String simpSessionId);
} }

View File

@ -25,7 +25,7 @@ public interface VitalSignsService {
* *
* @return * @return
*/ */
List<Map> getVitalSignsList(Connection connection); Map getVitalSignsList(Connection connection,String username, String dbName);
R getPatientInfo(String databaseName); R getPatientInfo(String databaseName);

View File

@ -16,6 +16,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.TextMessage;
@ -25,6 +26,7 @@ import java.io.IOException;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -32,29 +34,15 @@ import java.util.concurrent.ConcurrentHashMap;
@Service @Service
public class ChatServiceImpl implements ChatService { public class ChatServiceImpl implements ChatService {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@Autowired @Autowired
private SysUserService SysUserService; private SysUserService SysUserService;
private static final Map<String, CustomDataSource> datasourceMap = new ConcurrentHashMap<>(); private static final Map<String, CustomDataSource> datasourceMap = new ConcurrentHashMap<>();
private static final Map<String, Map<String, WebSocketSession>> databaseSessionMap = new ConcurrentHashMap<>(); //
// private static final Map<String, Map<String, WebSocketSession>> databaseSessionMap = new ConcurrentHashMap<>();
private static final Map<String, String> sessionDatabaseMap = new ConcurrentHashMap<>(); //
// private static final Map<String, String> sessionDatabaseMap = new ConcurrentHashMap<>();
// 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地址 // mysql地址
@Value("${vital-sign.mysql.host}") @Value("${vital-sign.mysql.host}")
@ -68,215 +56,66 @@ public class ChatServiceImpl implements ChatService {
@Value("${vital-sign.mysql.password}") @Value("${vital-sign.mysql.password}")
private String mysqlPassword; private String mysqlPassword;
@Override
public void sendMessage(String username, String patientName, String idNum, String date, String simpSessionId, String msg) {
CustomDataSource mongoDBSource = datasourceMap.get(simpSessionId);
if (mongoDBSource == null) {
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName);
datasourceMap.put(simpSessionId, mongoDBSource);
mongoDBSource.open();
}
SysUser sysUser = SysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
Map param = new HashMap();
MongoTemplate template = mongoDBSource.getConnection();
Document document = new Document();
document.put("content", msg);
param.put("content", msg);
String now = DateUtil.now();
document.put("create_time", now);
param.put("createTime", now);
document.put("create_user", username);
String name = sysUser.getName();
document.put("create_name", name);
param.put("createName", name);
document.put("deleted", 0);
document.put("revoked", 0);
template.insert(document, "t_chat");
simpMessagingTemplate.convertAndSendToUser(patientName + idNum + date, "/chatroomMessage", param);
}
@Override @Override
public void sendMessage(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) throws IOException { @Async
CustomDataSource mongoDBSource = datasourceMap.get(session.getId()); public void sendMessageMysql(String username, String patientName, String idNum, String msgType, WebSocketSession session, String msg, List<WebSocketSession> webSocketSessionList) throws SQLException, IOException {
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
synchronized (username) {
if (mongoDBSource == null) {
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName);
mongoDBSource.open();
datasourceMap.put(session.getId(), mongoDBSource);
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);
}
}
}
}
SysUser sysUser = SysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
if (StringUtils.hasText(msg)) {
JSONObject param = new JSONObject();
MongoTemplate template = mongoDBSource.getConnection();
Document document = new Document();
document.put("content", msg);
param.put("content", msg);
String now = DateUtil.now();
document.put("create_time", now);
param.put("createTime", now);
document.put("create_user", username);
String name = sysUser.getName();
document.put("create_name", name);
param.put("createName", name);
document.put("deleted", 0);
document.put("revoked", 0);
template.insert(document, "t_chat");
param.put("msgType", "msg");
Map<String, WebSocketSession> sessionMap = databaseSessionMap.get(databaseName);
for (Map.Entry<String, WebSocketSession> entry : sessionMap.entrySet()) {
WebSocketSession value = entry.getValue();
value.sendMessage(new TextMessage(param.toJSONString().getBytes()));
}
}
}
@Override
public void sendMessageMysql(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) {
CustomDataSource dataSource = datasourceMap.get(session.getId()); CustomDataSource dataSource = datasourceMap.get(session.getId());
// String databaseName = patientName + idNum;
String databaseName = idNum;
ArrayList<Map> history = new ArrayList<>();
if (dataSource == null) { if (dataSource == null) {
dataSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, databaseName); dataSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, idNum);
boolean status = dataSource.open(); boolean status = dataSource.open();
if (status) { if (status) {
datasourceMap.put(session.getId(), dataSource); datasourceMap.put(session.getId(), dataSource);
sessionDatabaseMap.put(session.getId(), databaseName); }else {
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);
}
}
String sql = "select content, create_time \"creatTime\", create_user \"createUser\", create_name \"createName\" from t_chat where deleted = 0 and revoked = 0 order by create_time asc ";
Connection connection = dataSource.getConnection();
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
Map map = new HashMap();
map.put("content", resultSet.getString("content"));
map.put("creatTime", resultSet.getString("creatTime"));
map.put("createUser", resultSet.getString("createUser"));
map.put("createName", resultSet.getString("createName"));
history.add(map);
}
JSONObject param = new JSONObject();
param.put("history", history);
param.put("msgType", "msg");
session.sendMessage(new TextMessage(param.toJSONString().getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
} else {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("status", 1); jsonObject.put("status", 1);
jsonObject.put("msg", "数据库未创建, 请重新连接。"); jsonObject.put("msg", "数据库未创建, 请重新连接。");
jsonObject.put("msgType", "msg"); jsonObject.put("msgType", "msg");
try { session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
session.close();
} catch (IOException e) {
e.printStackTrace();
}
return; return;
} }
} }
if (StringUtils.hasText(msg)) {
JSONObject param = new JSONObject();
SysUser sysUser = SysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
Connection connection = dataSource.getConnection(); // 发消息, 入库
try { if (StringUtils.hasText(msg)) {
Statement statement = connection.createStatement(); String now = DateUtil.now();
String sql = "CREATE TABLE `t_chat` (\n" +
" `id` int NOT NULL AUTO_INCREMENT,\n" + JSONObject param = new JSONObject();
" `content` varchar(5000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" + param.put("msgType", msgType);
" `create_time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" + param.put("createUser", username);
" `create_user` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" + param.put("createTime", now);
" `create_name` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" + param.put("content", msg);
" `deleted` bit(1) NULL DEFAULT NULL,\n" +
" `revoked` bit(1) NULL DEFAULT NULL,\n" + //System.out.println("param = " + param);
" PRIMARY KEY (`id`) USING BTREE\n" + //System.out.println("webSocketSessionList = " + webSocketSessionList);
") ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;"; // 广播消息
statement.execute(sql); for (WebSocketSession webSocketSession : webSocketSessionList) {
} catch (SQLException e) { webSocketSession.sendMessage(new TextMessage(param.toJSONString().getBytes()));
e.printStackTrace();
} }
// 入库
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = null; PreparedStatement preparedStatement = null;
try { try {
preparedStatement = connection.prepareStatement("INSERT INTO t_chat (content, create_time, create_user, create_name, deleted, revoked) VALUES (?, ?, ?, ?, ?, ?)"); preparedStatement = connection.prepareStatement("INSERT INTO t_chat (content, create_time, create_user, msg_type, deleted, revoked) VALUES (?, ?, ?, ?, ?, ?)");
preparedStatement.setString(1, msg); preparedStatement.setString(1, msg);
param.put("content", msg);
String now = DateUtil.now();
preparedStatement.setString(2, now); preparedStatement.setString(2, now);
param.put("createTime", now);
preparedStatement.setString(3, username); preparedStatement.setString(3, username);
param.put("createUser", username); // String name = sysUser.getName();
String name = sysUser.getName(); preparedStatement.setString(4, msgType);
preparedStatement.setString(4, name);
param.put("createName", name);
preparedStatement.setInt(5, 0); preparedStatement.setInt(5, 0);
preparedStatement.setInt(6, 0); preparedStatement.setInt(6, 0);
param.put("msgType", "msg");
preparedStatement.execute(); preparedStatement.execute();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
Map<String, WebSocketSession> sessionMap1 = databaseSessionMap.get(databaseName);
for (Map.Entry<String, WebSocketSession> entry : sessionMap1.entrySet()) {
WebSocketSession value = entry.getValue();
try {
value.sendMessage(new TextMessage(param.toJSONString().getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
} }
} }
@Override
public synchronized void stopTimerTask(String simpSessionId) {
CustomDataSource mongoDBSource = datasourceMap.get(simpSessionId);
if (mongoDBSource != null) {
mongoDBSource.close();
datasourceMap.remove(simpSessionId);
}
}
@Override @Override
public synchronized void stopTask(String simpSessionId) { public synchronized void stopTask(String simpSessionId) {
@ -285,14 +124,14 @@ public class ChatServiceImpl implements ChatService {
mongoDBSource.close(); mongoDBSource.close();
datasourceMap.remove(simpSessionId); datasourceMap.remove(simpSessionId);
} }
String databaseName = sessionDatabaseMap.get(simpSessionId); // String databaseName = sessionDatabaseMap.get(simpSessionId);
if (databaseName != null) { // if (databaseName != null) {
sessionDatabaseMap.remove(simpSessionId); // sessionDatabaseMap.remove(simpSessionId);
Map<String, WebSocketSession> stringWebSocketSessionMap = databaseSessionMap.get(databaseName); // Map<String, WebSocketSession> stringWebSocketSessionMap = databaseSessionMap.get(databaseName);
stringWebSocketSessionMap.remove(simpSessionId); // stringWebSocketSessionMap.remove(simpSessionId);
if (stringWebSocketSessionMap.isEmpty()) { // if (stringWebSocketSessionMap.isEmpty()) {
databaseSessionMap.remove(databaseName); // databaseSessionMap.remove(databaseName);
} // }
} // }
} }
} }

View File

@ -7,12 +7,14 @@ import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients; import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoIterable; import com.mongodb.client.MongoIterable;
import com.rax.common.core.util.R; import com.rax.common.core.util.R;
import com.rax.common.core.util.RedisUtils;
import com.rax.vital.common.datasource.MongoDBSource; import com.rax.vital.common.datasource.MongoDBSource;
import com.rax.vital.common.datasource.MySQLSource; import com.rax.vital.common.datasource.MySQLSource;
import com.rax.vital.common.util.DatabaseNameUtil; import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.v1.medicine.service.VitalSignsService; import com.rax.vital.v1.medicine.service.VitalSignsService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.bson.BsonRegularExpression; import org.bson.BsonRegularExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
@ -21,14 +23,14 @@ import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*; import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.time.Duration;
import java.util.HashMap; import java.util.*;
import java.util.List; import java.util.concurrent.TimeUnit;
import java.util.Map;
/** /**
* 生命体征数据 * 生命体征数据
@ -38,20 +40,6 @@ import java.util.Map;
@RefreshScope @RefreshScope
public class VitalSignServiceImpl implements VitalSignsService { public class VitalSignServiceImpl implements VitalSignsService {
@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;
@Value("${vital-sign.except-database}")
private String exceptDatabase;
@Value("${vital-sign.information-database}") @Value("${vital-sign.information-database}")
private String informationDatabase; private String informationDatabase;
@ -64,6 +52,10 @@ public class VitalSignServiceImpl implements VitalSignsService {
@Value("${vital-sign.mysql.username}") @Value("${vital-sign.mysql.username}")
private String mysqlUsername; private String mysqlUsername;
@Autowired
private RedisTemplate redisTemplate;
/** /**
* 获取生命体征最新一条数据 * 获取生命体征最新一条数据
* *
@ -96,15 +88,60 @@ public class VitalSignServiceImpl implements VitalSignsService {
} }
@Override @Override
public List<Map> getVitalSignsList(Connection connection) { public Map getVitalSignsList(Connection connection, String username, String dbName) {
// 获取生命体征数据, 10条
List<Map> vitalList = getVitalList(connection);
Collections.reverse(vitalList);
List<Map> last = (List<Map>) redisTemplate.opsForValue().get(dbName + "_" + username + "_vital_last");
if (last != null && !last.isEmpty()) {
if (redisTemplate.hasKey(dbName + "_" + username + "_vital")) {
// 数据有变化, 更新缓存
if (!last.get(last.size() - 1).get("Time").equals(vitalList.get(vitalList.size() - 1).get("Time"))) {
// 比较last和vitalList 计算出需要更新的条目
for (int i = 0; i < vitalList.size(); i++) {
if (last.get(last.size() - 1).get("Time").equals(vitalList.get(i).get("Time"))) {
List<Map> updateList = vitalList.subList(i, vitalList.size());
// todo delete
// System.out.println("updateList = " + updateList);
for (Map map : updateList) {
// ->
redisTemplate.opsForList().rightPush(dbName + "_" + username + "_vital", map);
}
// 更新缓存
redisTemplate.delete(dbName + "_" + username + "_vital_last");
redisTemplate.opsForValue().set(dbName + "_" + username + "_vital_last", vitalList, 100, TimeUnit.SECONDS);
break;
}
}
}
}else {
// 缓存中没有数据,存进去, ->
redisTemplate.opsForList().rightPushAll(dbName + "_" + username + "_vital", last);
redisTemplate.opsForList().trim(dbName + "_" + username + "_vital", 0, 10);
// 设置过期时间
redisTemplate.expire(dbName + "_" + username + "_vital", Duration.ofSeconds(100));
}
// 右进左出
Object o = redisTemplate.opsForList().leftPop(dbName + "_" + username + "_vital");
return (Map) o;
}
// 第一个缓存存储上一次查询到的数据
redisTemplate.opsForValue().set(dbName + "_" + username + "_vital_last", vitalList, 100, TimeUnit.SECONDS);
return Map.of();
}
private List<Map> getVitalList(Connection connection) {
List<Map> vitalList = new ArrayList<>(); List<Map> vitalList = new ArrayList<>();
try { try {
Statement statement = connection.createStatement(); // 查询生命体征数据
String sql = "SELECT Phase, BIS, HR, SBP, DBP, ST, TEMP, SPO2, EtCO2, PPG, ABG, TOF, Time " + String sql2 = "SELECT id,Phase, BIS, HR, SBP, DBP, ST, TEMP, SPO2, EtCO2, PPG, ABG, TOF, Time " +
" FROM `featuretable` " + " FROM `featuretable` " +
" GROUP BY Phase, BIS, HR, SBP, DBP, ST, TEMP, SPO2, EtCO2, PPG, ABG, TOF, Time " + // " GROUP BY Phase, BIS, HR, SBP, DBP, ST, TEMP, SPO2, EtCO2, PPG, ABG, TOF, Time " +
" ORDER BY time DESC LIMIT 10;"; " ORDER BY id DESC LIMIT 20;";
ResultSet resultSet = statement.executeQuery(sql); PreparedStatement statement = connection.prepareStatement(sql2);
ResultSet resultSet = statement.executeQuery(sql2);
while (resultSet.next()) { while (resultSet.next()) {
Map<String, Object> vital = new HashMap(); Map<String, Object> vital = new HashMap();
vital.put("Phase", resultSet.getString("Phase")); vital.put("Phase", resultSet.getString("Phase"));
@ -120,7 +157,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
vital.put("ABG", resultSet.getString("ABG")); vital.put("ABG", resultSet.getString("ABG"));
vital.put("TOF", resultSet.getString("TOF")); vital.put("TOF", resultSet.getString("TOF"));
vital.put("Time", resultSet.getString("Time")); vital.put("Time", resultSet.getString("Time"));
Double bis = resultSet.getDouble("BIS"); Double bis = resultSet.getDouble("BIS");
vital.put("BIS_except", bis <= 40 || bis >= 60); vital.put("BIS_except", bis <= 40 || bis >= 60);
Double hr = resultSet.getDouble("HR"); Double hr = resultSet.getDouble("HR");
vital.put("HR_except", hr <= 50 || hr >= 80); vital.put("HR_except", hr <= 50 || hr >= 80);
@ -134,14 +171,15 @@ public class VitalSignServiceImpl implements VitalSignsService {
vital.put("EtCO2_except", etCO2 <= 30 || etCO2 >= 45); vital.put("EtCO2_except", etCO2 <= 30 || etCO2 >= 45);
vitalList.add(vital); vitalList.add(vital);
} }
return vitalList;
} catch (SQLException e) { } catch (SQLException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return vitalList;
} }
public R getPatientInfo(String databaseName) { public R getPatientInfo(String databaseName) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName); MongoDBSource mongoDBSource = new MongoDBSource(databaseName);
mongoDBSource.open(); mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection(); MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query(); Query query = new Query();
@ -183,25 +221,25 @@ public class VitalSignServiceImpl implements VitalSignsService {
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
mySQLSource.close();
return R.ok(map); return R.ok(map);
} }
@Override @Override
public R getDatabaseList() { public R getDatabaseList() {
MongoClientSettings.Builder mongoBuilder = MongoClientSettings.builder(); //MongoClientSettings.Builder mongoBuilder = MongoClientSettings.builder();
// mongodb://账户:密码@ip:端口/?authSource=admin //// mongodb://账户:密码@ip:端口/?authSource=admin
String connectionUrl = "mongodb://" + mongoUsername + ":" + mongoPassword + "@" + mongoDBHost + "/" + "?authSource=admin"; //String connectionUrl = "mongodb://" + mongoUsername + ":" + mongoPassword + "@" + mongoDBHost + "/" + "?authSource=admin";
mongoBuilder.applyConnectionString(new ConnectionString(connectionUrl)); //mongoBuilder.applyConnectionString(new ConnectionString(connectionUrl));
MongoClient mongoClient = MongoClients.create(mongoBuilder.build(), SpringDataMongoDB.driverInformation()); //MongoClient mongoClient = MongoClients.create(mongoBuilder.build(), SpringDataMongoDB.driverInformation());
MongoIterable<String> databaseNames = mongoClient.listDatabaseNames(); //MongoIterable<String> databaseNames = mongoClient.listDatabaseNames();
for (String database : databaseNames) { //for (String database : databaseNames) {
} //}
return null; return null;
} }
public Page getPatientPage(String name, String dept, long offset, int limit) { public Page getPatientPage(String name, String dept, long offset, int limit) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase); MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open(); mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection(); MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query(); Query query = new Query();
@ -231,7 +269,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
@Override @Override
public List getSurgeryCount(String start, String end) { public List getSurgeryCount(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase); MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open(); mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection(); MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>(); List<AggregationOperation> operations = new ArrayList<>();
@ -270,7 +308,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
} }
public List getSurgeryDuration(String start, String end) { public List getSurgeryDuration(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase); MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open(); mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection(); MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>(); List<AggregationOperation> operations = new ArrayList<>();
@ -319,7 +357,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
} }
public List getSurgeryTypeProportion(String start, String end) { public List getSurgeryTypeProportion(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase); MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open(); mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection(); MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>(); List<AggregationOperation> operations = new ArrayList<>();
@ -339,7 +377,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
} }
public List getSurgeryOtherDuration(String start, String end) { public List getSurgeryOtherDuration(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase); MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open(); mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection(); MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>(); List<AggregationOperation> operations = new ArrayList<>();
@ -387,7 +425,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
@Override @Override
public List getPatientSurgeryList(String name, String code, String surgery, String type) { public List getPatientSurgeryList(String name, String code, String surgery, String type) {
if (StringUtils.hasText(code)) { if (StringUtils.hasText(code)) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase); MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open(); mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection(); MongoTemplate template = mongoDBSource.getConnection();
@ -437,7 +475,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
public List getSurgeryTableData(String name, String code, String date, String table) { public List getSurgeryTableData(String name, String code, String date, String table) {
if (StringUtils.hasText(code)) { if (StringUtils.hasText(code)) {
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase); MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open(); mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection(); MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query(); Query query = new Query();
@ -452,7 +490,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
mongoDBSource.close(); mongoDBSource.close();
} }
String database = DatabaseNameUtil.encrypt(name) + "_" + DatabaseNameUtil.encrypt(code) + "_" + date; String database = DatabaseNameUtil.encrypt(name) + "_" + DatabaseNameUtil.encrypt(code) + "_" + date;
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database); MongoDBSource mongoDBSource = new MongoDBSource(database);
mongoDBSource.open(); mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection(); MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query(); Query query = new Query();

View File

@ -96,7 +96,7 @@ public class VitalSignTimer {
MongoDBSource mongoDBSource = mongoDBSourceMap.get(simpSessionId); MongoDBSource mongoDBSource = mongoDBSourceMap.get(simpSessionId);
if (mongoDBSource == null) { if (mongoDBSource == null) {
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database); mongoDBSource = new MongoDBSource(database);
mongoDBSourceMap.put(simpSessionId, mongoDBSource); mongoDBSourceMap.put(simpSessionId, mongoDBSource);
mongoDBSource.open(); mongoDBSource.open();
} }
@ -155,8 +155,8 @@ public class VitalSignTimer {
public void run() { public void run() {
HashMap<String, Object> result = new HashMap(); HashMap<String, Object> result = new HashMap();
Connection connection = finalMySQLSource.getConnection(); Connection connection = finalMySQLSource.getConnection();
List<Map> vitalSignsList = vitalSignsService.getVitalSignsList(connection); // List<Map> vitalSignsList = vitalSignsService.getVitalSignsList(connection);
result.put("vitalSignsList", vitalSignsList); // result.put("vitalSignsList", vitalSignsList);
List<Map> aiMedicineList = aiMedicineService.getAIMedicine(connection); List<Map> aiMedicineList = aiMedicineService.getAIMedicine(connection);
result.put("aiMedicineList", aiMedicineList); result.put("aiMedicineList", aiMedicineList);
List<Map> docMedicineList = doctorMedicineService.getDocMedicine(connection); List<Map> docMedicineList = doctorMedicineService.getDocMedicine(connection);
@ -216,7 +216,7 @@ public class VitalSignTimer {
if (masterControlMap.containsKey(database) && masterControlMap.get(database).equals(username)) { if (masterControlMap.containsKey(database) && masterControlMap.get(database).equals(username)) {
MongoDBSource mongoDBSource = mongoDBSourceMap.get(simpSessionId); MongoDBSource mongoDBSource = mongoDBSourceMap.get(simpSessionId);
if (mongoDBSource == null) { if (mongoDBSource == null) {
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database); mongoDBSource = new MongoDBSource(database);
mongoDBSourceMap.put(simpSessionId, mongoDBSource); mongoDBSourceMap.put(simpSessionId, mongoDBSource);
mongoDBSource.open(); mongoDBSource.open();
} }

View File

@ -99,7 +99,7 @@ public class VitalSignTimerWS {
CustomDataSource dataSource = dataSourceMap.get(sessionId); CustomDataSource dataSource = dataSourceMap.get(sessionId);
if (dataSource == null) { if (dataSource == null) {
dataSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database); dataSource = new MongoDBSource(database);
dataSourceMap.put(sessionId, dataSource); dataSourceMap.put(sessionId, dataSource);
dataSource.open(); dataSource.open();
} }
@ -139,11 +139,11 @@ public class VitalSignTimerWS {
} }
public void createAndSendMessageMySQL(String database, String username, WebSocketSession session) { public void createAndSendMessageMySQL(String database, String username, WebSocketSession session) {
synchronized (username) { // synchronized (username) {
if (!masterControlMap.containsKey(database)) { if (!masterControlMap.containsKey(database)) {
masterControlMap.put(database, username); masterControlMap.put(database, username);
}
} }
// }
String sessionId = session.getId(); String sessionId = session.getId();
@ -177,10 +177,10 @@ public class VitalSignTimerWS {
TimerTask timerTask = new TimerTask() { TimerTask timerTask = new TimerTask() {
@Override @Override
public void run() { public void run() {
Connection connection = finalDataSource.getConnection(); Connection connection = finalDataSource.getConnection();
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
List<Map> vitalSignsList = vitalSignsService.getVitalSignsList(connection); // List<Map> vitalSignsList = vitalSignsService.getVitalSignsList(connection);
Map vitalSignsList = vitalSignsService.getVitalSignsList(connection, username, database);
jsonObject.put("vitalSignsList", vitalSignsList); jsonObject.put("vitalSignsList", vitalSignsList);
List<Map> aiMedicineList = aiMedicineService.getAIMedicine(connection); List<Map> aiMedicineList = aiMedicineService.getAIMedicine(connection);
jsonObject.put("aiMedicineList", aiMedicineList); jsonObject.put("aiMedicineList", aiMedicineList);

View File

@ -8,6 +8,7 @@ import com.rax.vital.common.util.GetHttpParamUtil;
import com.rax.vital.common.util.SysLoggerBuilder; import com.rax.vital.common.util.SysLoggerBuilder;
import com.rax.vital.common.util.TokenUtil; import com.rax.vital.common.util.TokenUtil;
import com.rax.vital.v2.timer.AIMedicineTimer; import com.rax.vital.v2.timer.AIMedicineTimer;
import com.rax.vital.v2.timer.HeartBeatTimer;
import com.rax.vital.v2.timer.VitalSignTimerV2; import com.rax.vital.v2.timer.VitalSignTimerV2;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -40,16 +41,16 @@ public class AddMedicineHandler implements WebSocketHandler {
@Autowired @Autowired
private AIMedicineTimer aiMedicineTimer; private AIMedicineTimer aiMedicineTimer;
// 发送心跳任务的定时任务容器 @Autowired
private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap<>(); private HeartBeatTimer heartBeatTimer;
private String SERVICE_NAME = HeartBeatTimer.addMedicineHandler;
@Override @Override
public void afterConnectionEstablished(WebSocketSession session) { public void afterConnectionEstablished(WebSocketSession session) {
startHeartbeat(session); heartBeatTimer.putSession(SERVICE_NAME,session);
} }
@Override @Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
@ -124,7 +125,7 @@ public class AddMedicineHandler implements WebSocketHandler {
@Override @Override
public void handleTransportError(WebSocketSession session, Throwable exception) { public void handleTransportError(WebSocketSession session, Throwable exception) {
stopHeartbeat(session); heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session); aiMedicineTimer.closeConnection(session);
SysLog sysLog = sysLoggerBuilder.buildSysLog("给药接口异常中断:"+exception.getMessage(), "4", session); SysLog sysLog = sysLoggerBuilder.buildSysLog("给药接口异常中断:"+exception.getMessage(), "4", session);
sysLogService.saveLog(sysLog); sysLogService.saveLog(sysLog);
@ -132,7 +133,8 @@ public class AddMedicineHandler implements WebSocketHandler {
@Override @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
stopHeartbeat(session); //stopHeartbeat(session);
heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session); aiMedicineTimer.closeConnection(session);
SysLog sysLog = sysLoggerBuilder.buildSysLog("给药接口客户端,断开连接", "0", session); SysLog sysLog = sysLoggerBuilder.buildSysLog("给药接口客户端,断开连接", "0", session);
sysLogService.saveLog(sysLog); sysLogService.saveLog(sysLog);
@ -143,33 +145,6 @@ public class AddMedicineHandler implements WebSocketHandler {
return false; return false;
} }
private void startHeartbeat(WebSocketSession session) {
if (!timerTaskMap.containsKey(session.getId())) {
ScheduledExecutorService heartbeatExecutor = Executors.newScheduledThreadPool(1);
heartbeatExecutor.scheduleAtFixedRate(() -> {
try {
if (session.isOpen()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msgType", "heartbeat");
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else {
stopHeartbeat(session);
aiMedicineTimer.closeConnection(session);
session.close();
}
} catch (Exception e) {
e.printStackTrace();
stopHeartbeat(session);
}
}, 0, 30, TimeUnit.SECONDS);
timerTaskMap.put(session.getId(), heartbeatExecutor);
}
}
private void stopHeartbeat(WebSocketSession session) {
ScheduledExecutorService heartbeatExecutor = timerTaskMap.get(session.getId());
heartbeatExecutor.shutdownNow();
}
// 异步发送消息 // 异步发送消息
private void sendMsgAsync(WebSocketSession session, JSONObject jsonObject) { private void sendMsgAsync(WebSocketSession session, JSONObject jsonObject) {
@ -178,12 +153,12 @@ public class AddMedicineHandler implements WebSocketHandler {
if (session.isOpen()) { if (session.isOpen()) {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes())); session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
}else { }else {
stopHeartbeat(session); heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session); aiMedicineTimer.closeConnection(session);
session.close(); session.close();
} }
}catch (Exception e) { }catch (Exception e) {
stopHeartbeat(session); heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session); aiMedicineTimer.closeConnection(session);
log.error("addMedicineHandler-sendMsgAsync error: {}", e.getMessage()); log.error("addMedicineHandler-sendMsgAsync error: {}", e.getMessage());
} }

View File

@ -1,23 +1,28 @@
package com.rax.vital.v2.handler; package com.rax.vital.v2.handler;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.admin.api.entity.SysLog; import com.rax.admin.api.entity.SysLog;
import com.rax.admin.service.SysLogService; import com.rax.admin.service.SysLogService;
import com.rax.vital.common.datasource.MongoDBSource;
import com.rax.vital.common.util.DatabaseNameUtil; import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.common.util.GetHttpParamUtil; import com.rax.vital.common.util.GetHttpParamUtil;
import com.rax.vital.common.util.SysLoggerBuilder; import com.rax.vital.common.util.SysLoggerBuilder;
import com.rax.vital.common.util.TokenUtil; import com.rax.vital.common.util.TokenUtil;
import com.rax.vital.v2.medicine.service.ChatService; import com.rax.vital.v2.medicine.service.ChatService;
import com.rax.vital.v2.timer.HeartBeatTimer;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.socket.*; import org.springframework.web.socket.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Component @Component
public class ChatHandler implements WebSocketHandler { public class ChatHandler implements WebSocketHandler {
@ -34,11 +39,24 @@ public class ChatHandler implements WebSocketHandler {
@Autowired @Autowired
private TokenUtil tokenUtil; private TokenUtil tokenUtil;
private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap(); @Autowired
private HeartBeatTimer heartBeatTimer;
private String SERVICE_NAME = HeartBeatTimer.chatHandler;
private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(5);
// dbName -> sessionList
private Map<String, List<WebSocketSession>> dbNameSessionList = new ConcurrentHashMap();
// sessionId -> dbName
private Map<String, String> sessionDbMap = new ConcurrentHashMap();
@Override @Override
public void afterConnectionEstablished(WebSocketSession session) { public void afterConnectionEstablished(WebSocketSession session) {
startHeartbeat(session); heartBeatTimer.putSession(SERVICE_NAME, session);
} }
@Override @Override
@ -47,34 +65,66 @@ public class ChatHandler implements WebSocketHandler {
String payload = (String) message.getPayload(); String payload = (String) message.getPayload();
JSONObject jsonObject = JSONObject.parseObject(payload); JSONObject jsonObject = JSONObject.parseObject(payload);
if (!"heartbeat".equals(jsonObject.getString("msgType"))) {
String msgType = jsonObject.getString("msgType");
String patientName = jsonObject.getString("patientName");
String idNum = jsonObject.getString("idNum");
String date = jsonObject.getString("date");
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
if ("init".equals(msgType)) {
if (!dbNameSessionList.containsKey(databaseName)) {
ArrayList<WebSocketSession> sessionArrayList = new ArrayList<>();
dbNameSessionList.put(databaseName, sessionArrayList);
sessionDbMap.put(session.getId(), databaseName);
}
List<WebSocketSession> webSocketSessions = dbNameSessionList.get(databaseName);
webSocketSessions.add(session);
}
// 处理音频或文本
if ("msg".equals(msgType) || "audio".equals(msgType)) {
String query = Objects.requireNonNull(session.getUri()).getQuery(); String query = Objects.requireNonNull(session.getUri()).getQuery();
String token = GetHttpParamUtil.getParam(query, "token"); String token = GetHttpParamUtil.getParam(query, "token");
Map<String, Object> map = tokenUtil.parseToken(token); Map<String, Object> map = tokenUtil.parseToken(token);
String username = (String) map.get("username"); String username = (String) map.get("username");
String patientName = jsonObject.getString("patientName");
String idNum = jsonObject.getString("idNum");
String date = jsonObject.getString("date");
// 消息内容 // 消息内容
String msg = jsonObject.getString("msg"); String content = jsonObject.getString("content");
String databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date; List<WebSocketSession> webSocketSessions = dbNameSessionList.get(databaseName);
chatService.sendMessage(databaseName, username, session, msg); // 转发消息
JSONObject param = new JSONObject();
param.put("msgType", msgType);
param.put("createUser", username);
param.put("createTime", DateUtil.now());
param.put("content", content);
for (WebSocketSession webSocketSession : webSocketSessions) {
if (webSocketSession.isOpen()) {
System.out.println("发消息啦 = " + param.toJSONString());
webSocketSession.sendMessage(new TextMessage(param.toJSONString().getBytes()));
}
}
//异步入库mongodb
EXECUTOR_SERVICE.execute(() -> insertCollection(databaseName, param));
// 之前的
// chatService.sendMessage(databaseName, username, session, content);
} }
} }
@Override @Override
public void handleTransportError(WebSocketSession session, Throwable exception) { public void handleTransportError(WebSocketSession session, Throwable exception) {
SysLog sysLog = sysLoggerBuilder.buildSysLog("聊天室接口异常中断:"+exception.getMessage(), "4", session); SysLog sysLog = sysLoggerBuilder.buildSysLog("聊天室接口异常中断:" + exception.getMessage(), "4", session);
sysLogService.saveLog(sysLog); sysLogService.saveLog(sysLog);
} }
@Override @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
stopHeartbeat(session); heartBeatTimer.removeSession(session);
chatService.stopTask(session.getId()); chatService.stopTask(session.getId());
SysLog sysLog = sysLoggerBuilder.buildSysLog("聊天室接口关闭", "0", session); SysLog sysLog = sysLoggerBuilder.buildSysLog("聊天室接口关闭", "0", session);
sysLogService.saveLog(sysLog); sysLogService.saveLog(sysLog);
@ -85,31 +135,18 @@ public class ChatHandler implements WebSocketHandler {
return false; return false;
} }
private void startHeartbeat(WebSocketSession session) { // 入库mongodb
if (!timerTaskMap.containsKey(session.getId())) { private void insertCollection(String dbName, JSONObject jsonObject) {
ScheduledExecutorService heartbeatExecutor = Executors.newScheduledThreadPool(1); MongoDBSource mongoDBSource = new MongoDBSource(dbName);
heartbeatExecutor.scheduleAtFixedRate(() -> { mongoDBSource.open();
try { MongoTemplate mongoTemplate = mongoDBSource.getConnection();
if (session.isOpen()) { Document document = new Document();
JSONObject jsonObject = new JSONObject(); document.put("msgType", jsonObject.getString("msgType"));
jsonObject.put("msgType", "heartbeat"); document.put("createUser", jsonObject.getString("createUser"));
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes())); document.put("createTime", jsonObject.getString("createTime"));
} else { document.put("content", jsonObject.getString("content"));
stopHeartbeat(session); mongoTemplate.insert(jsonObject, "t_chat");
chatService.stopTask(session.getId()); mongoDBSource.close();
session.close();
}
} catch (Exception e) {
e.printStackTrace();
stopHeartbeat(session);
}
}, 0, 10, TimeUnit.SECONDS);
timerTaskMap.put(session.getId(), heartbeatExecutor);
}
} }
private void stopHeartbeat(WebSocketSession session) {
ScheduledExecutorService heartbeatExecutor = timerTaskMap.get(session.getId());
heartbeatExecutor.shutdownNow();
}
} }

View File

@ -6,6 +6,7 @@ import com.rax.admin.service.SysLogService;
import com.rax.vital.common.util.DatabaseNameUtil; import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.common.util.SysLoggerBuilder; import com.rax.vital.common.util.SysLoggerBuilder;
import com.rax.vital.v2.timer.AIMedicineTimer; import com.rax.vital.v2.timer.AIMedicineTimer;
import com.rax.vital.v2.timer.HeartBeatTimer;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -35,13 +36,19 @@ public class MachineFeedbackHandler implements WebSocketHandler {
@Autowired @Autowired
private AIMedicineTimer aiMedicineTimer; private AIMedicineTimer aiMedicineTimer;
@Autowired
private HeartBeatTimer heartBeatTimer;
private String SERVICE_NAME = HeartBeatTimer.machineFeedbackHandler;
@Override @Override
public void afterConnectionEstablished(WebSocketSession session) throws IOException { public void afterConnectionEstablished(WebSocketSession session) throws IOException {
JSONObject msg = new JSONObject(); JSONObject msg = new JSONObject();
msg.put("msgType", "msg"); msg.put("msgType", "msg");
msg.put("msg", "已成功连接服务器!"); msg.put("msg", "已成功连接服务器!");
session.sendMessage(new TextMessage(msg.toJSONString().getBytes())); session.sendMessage(new TextMessage(msg.toJSONString().getBytes()));
startHeartbeat(session); heartBeatTimer.putSession(SERVICE_NAME,session);
} }
@Override @Override
@ -141,7 +148,7 @@ public class MachineFeedbackHandler implements WebSocketHandler {
@Override @Override
public void handleTransportError(WebSocketSession session, Throwable exception) { public void handleTransportError(WebSocketSession session, Throwable exception) {
stopHeartbeat(session); heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session); aiMedicineTimer.closeConnection(session);
SysLog sysLog = sysLoggerBuilder.buildSysLog("仪器端获取收药口异常中断", "4", session); SysLog sysLog = sysLoggerBuilder.buildSysLog("仪器端获取收药口异常中断", "4", session);
sysLogService.saveLog(sysLog); sysLogService.saveLog(sysLog);
@ -149,7 +156,7 @@ public class MachineFeedbackHandler implements WebSocketHandler {
@Override @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
stopHeartbeat(session); heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session); aiMedicineTimer.closeConnection(session);
SysLog sysLog = sysLoggerBuilder.buildSysLog("仪器端收药接口关闭", "0", session); SysLog sysLog = sysLoggerBuilder.buildSysLog("仪器端收药接口关闭", "0", session);
sysLogService.saveLog(sysLog); sysLogService.saveLog(sysLog);
@ -160,33 +167,6 @@ public class MachineFeedbackHandler implements WebSocketHandler {
return false; return false;
} }
private void startHeartbeat(WebSocketSession session) {
if (!timerTaskMap.containsKey(session.getId())) {
ScheduledExecutorService heartbeatExecutor = Executors.newScheduledThreadPool(1);
heartbeatExecutor.scheduleAtFixedRate(() -> {
try {
if (session.isOpen()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msgType", "heartbeat");
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else {
stopHeartbeat(session);
aiMedicineTimer.closeConnection(session);
session.close();
}
} catch (Exception e) {
e.printStackTrace();
stopHeartbeat(session);
}
}, 0, 30, TimeUnit.SECONDS);
timerTaskMap.put(session.getId(), heartbeatExecutor);
}
}
private void stopHeartbeat(WebSocketSession session) {
ScheduledExecutorService heartbeatExecutor = timerTaskMap.get(session.getId());
heartbeatExecutor.shutdownNow();
}
// 异步发送消息 // 异步发送消息
private void sendMsgAsync(WebSocketSession session, JSONObject jsonObject) { private void sendMsgAsync(WebSocketSession session, JSONObject jsonObject) {
@ -195,12 +175,12 @@ public class MachineFeedbackHandler implements WebSocketHandler {
if (session.isOpen()) { if (session.isOpen()) {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes())); session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else { } else {
stopHeartbeat(session); heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session); aiMedicineTimer.closeConnection(session);
session.close(); session.close();
} }
} catch (Exception e) { } catch (Exception e) {
stopHeartbeat(session); heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session); aiMedicineTimer.closeConnection(session);
log.error("addMedicineHandler-sendMsgAsync error: {}", e.getMessage()); log.error("addMedicineHandler-sendMsgAsync error: {}", e.getMessage());
} }

View File

@ -7,6 +7,7 @@ import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.common.util.GetHttpParamUtil; import com.rax.vital.common.util.GetHttpParamUtil;
import com.rax.vital.common.util.SysLoggerBuilder; import com.rax.vital.common.util.SysLoggerBuilder;
import com.rax.vital.common.util.TokenUtil; import com.rax.vital.common.util.TokenUtil;
import com.rax.vital.v2.timer.HeartBeatTimer;
import com.rax.vital.v2.timer.VitalSignTimerV2; import com.rax.vital.v2.timer.VitalSignTimerV2;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -39,11 +40,17 @@ public class MedicineHandler implements WebSocketHandler {
@Autowired @Autowired
private TokenUtil tokenUtil; private TokenUtil tokenUtil;
private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap<>();
// 全局心跳任务容器
@Autowired
private HeartBeatTimer heartBeatTimer;
private String SERVICE_NAME = HeartBeatTimer.medicineHandler;
@Override @Override
public void afterConnectionEstablished(WebSocketSession session) { public void afterConnectionEstablished(WebSocketSession session) {
startHeartbeat(session); heartBeatTimer.putSession(SERVICE_NAME,session);
} }
@Override @Override
@ -70,7 +77,7 @@ public class MedicineHandler implements WebSocketHandler {
@Override @Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
stopHeartbeat(session); heartBeatTimer.removeSession(session);
vitalSignTimerV2.stopTimerTask(session.getId()); vitalSignTimerV2.stopTimerTask(session.getId());
SysLog sysLog = sysLoggerBuilder.buildSysLog("生命体征接口异常中断", "4", session); SysLog sysLog = sysLoggerBuilder.buildSysLog("生命体征接口异常中断", "4", session);
sysLogService.saveLog(sysLog); sysLogService.saveLog(sysLog);
@ -78,7 +85,7 @@ public class MedicineHandler implements WebSocketHandler {
@Override @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
stopHeartbeat(session); heartBeatTimer.removeSession(session);
vitalSignTimerV2.stopTimerTask(session.getId()); vitalSignTimerV2.stopTimerTask(session.getId());
SysLog sysLog = sysLoggerBuilder.buildSysLog("生命体征接口连接关闭", "0", session); SysLog sysLog = sysLoggerBuilder.buildSysLog("生命体征接口连接关闭", "0", session);
sysLogService.saveLog(sysLog); sysLogService.saveLog(sysLog);
@ -89,31 +96,4 @@ public class MedicineHandler implements WebSocketHandler {
return false; return false;
} }
private void startHeartbeat(WebSocketSession session) {
if (!timerTaskMap.containsKey(session.getId())) {
ScheduledExecutorService heartbeatExecutor = Executors.newScheduledThreadPool(1);
heartbeatExecutor.scheduleAtFixedRate(() -> {
try {
if (session.isOpen()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msgType", "heartbeat");
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else {
session.close();
stopHeartbeat(session);
vitalSignTimerV2.stopTimerTask(session.getId());
}
} catch (Exception e) {
e.printStackTrace();
stopHeartbeat(session);
}
}, 0, 10, TimeUnit.SECONDS);
timerTaskMap.put(session.getId(), heartbeatExecutor);
}
}
private void stopHeartbeat(WebSocketSession session) {
ScheduledExecutorService heartbeatExecutor = timerTaskMap.get(session.getId());
heartbeatExecutor.shutdownNow();
}
} }

View File

@ -44,6 +44,13 @@ public class WebSocketInterceptors implements HandshakeInterceptor {
@Override @Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
String query = request.getURI().getQuery(); String query = request.getURI().getQuery();
if (query == null) {
return false;
}
Map<String, String> params = GetHttpParamUtil.getParams(query);
if (!params.containsKey("token")) {
return false;
}
String token = GetHttpParamUtil.getParam(query, "token"); String token = GetHttpParamUtil.getParam(query, "token");
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (authorization == null) { if (authorization == null) {

View File

@ -37,36 +37,11 @@ public class ChatServiceImpl implements ChatService {
private static final Map<String, String> sessionDatabaseMap = new ConcurrentHashMap<>(); private static final Map<String, String> sessionDatabaseMap = new ConcurrentHashMap<>();
// 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;
@Override @Override
public void sendMessage(String databaseName, String username, WebSocketSession session, String msg) throws IOException { public void sendMessage(String databaseName, String username, WebSocketSession session, String msg) throws IOException {
CustomDataSource mongoDBSource = datasourceMap.get(session.getId()); CustomDataSource mongoDBSource = datasourceMap.get(session.getId());
if (mongoDBSource == null) { if (mongoDBSource == null) {
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName); mongoDBSource = new MongoDBSource(databaseName);
mongoDBSource.open(); mongoDBSource.open();
datasourceMap.put(session.getId(), mongoDBSource); datasourceMap.put(session.getId(), mongoDBSource);
sessionDatabaseMap.put(session.getId(), databaseName); sessionDatabaseMap.put(session.getId(), databaseName);

View File

@ -290,7 +290,7 @@ public class MedicineService implements IMedicineService {
} }
} }
String database = DatabaseNameUtil.encrypt(name) + "_" + DatabaseNameUtil.encrypt(code) + "_" + date; String database = DatabaseNameUtil.encrypt(name) + "_" + DatabaseNameUtil.encrypt(code) + "_" + date;
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database); MongoDBSource mongoDBSource = new MongoDBSource(database);
mongoDBSource.open(); mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection(); MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query(); Query query = new Query();

View File

@ -0,0 +1,88 @@
package com.rax.vital.v2.timer;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @project_name: rax-remote-v2
* @time: 2024/11/13 17:01
* @author: republicline
* @description: 全局心跳任务实现
*/
@Component
@Data
public class HeartBeatTimer {
public static final String chatHandler = "chatHandler";
public static final String addMedicineHandler = "addMedicineHandler";
public static final String machineFeedbackHandler = "machineFeedbackHandler";
public static final String medicineHandler = "medicineHandler";
private static final Map<String, Map<String, WebSocketSession>> serviceSessionMap = new ConcurrentHashMap<>();
static {
// 初始化4个Map分别对应4个不同业务模块的WebSocketSession
Map<String, WebSocketSession> chatHeartBeat = new ConcurrentHashMap<>();
Map<String, WebSocketSession> addMedicineHeartBeat = new ConcurrentHashMap<>();
Map<String, WebSocketSession> machineFeedbackHeartBeat = new ConcurrentHashMap<>();
Map<String, WebSocketSession> medicineHeartBeat = new ConcurrentHashMap<>();
serviceSessionMap.put(chatHandler, chatHeartBeat);
serviceSessionMap.put(machineFeedbackHandler, addMedicineHeartBeat);
serviceSessionMap.put(addMedicineHandler, machineFeedbackHeartBeat);
serviceSessionMap.put(medicineHandler, medicineHeartBeat);
}
@Scheduled(fixedRate = 30000)
private void sendHeartbeat() {
// 遍历urlSessionMap的session数量 调试使用
serviceSessionMap.keySet().forEach(url -> {
Map<String, WebSocketSession> handlerMap = serviceSessionMap.get(url);
for (WebSocketSession value : handlerMap.values()) {
System.out.println("url: " + url + " session: " + value.getId());
}
});
for (Map<String, WebSocketSession> handlerMap : serviceSessionMap.values()) {
for (WebSocketSession session : handlerMap.values()) {
try {
if (session.isOpen()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msgType", "heartbeat");
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else {
handlerMap.remove(session.getId());
session.close();
}
} catch (Exception e) {
handlerMap.remove(session.getId());
e.printStackTrace();
}
}
}
}
// 向指定业务模块的sessionMap中添加到urlSessionMap
public void putSession(String url, WebSocketSession session) {
Map<String, WebSocketSession> handlerMap = serviceSessionMap.get(url);
if (handlerMap == null) {
return;
}
handlerMap.put(session.getId(), session);
}
// 从指定业务模块的urlSessionMap移除session
public void removeSession(WebSocketSession session) {
serviceSessionMap.values().forEach(handlerMap -> handlerMap.remove(session.getId()));
}
}

View File

@ -31,17 +31,6 @@ import java.util.concurrent.ConcurrentHashMap;
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
public class VitalSignTimerV2 { public class VitalSignTimerV2 {
// 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;
private final SurgeryServiceV2 surgeryServiceV2; private final SurgeryServiceV2 surgeryServiceV2;
@ -77,7 +66,7 @@ public class VitalSignTimerV2 {
CustomDataSource dataSource = dataSourceMap.get(sessionId); CustomDataSource dataSource = dataSourceMap.get(sessionId);
if (dataSource == null) { if (dataSource == null) {
dataSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database); dataSource = new MongoDBSource(database);
dataSourceMap.put(sessionId, dataSource); dataSourceMap.put(sessionId, dataSource);
dataSource.open(); dataSource.open();
} }
@ -88,8 +77,8 @@ public class VitalSignTimerV2 {
MongoTemplate template = finalMongoDBSource.getConnection(); MongoTemplate template = finalMongoDBSource.getConnection();
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
// 生命体征信息 // 生命体征信息 这里要改改
List vitalSignsList = surgeryServiceV2.getVitalSignsList(template); List<Map> vitalSignsList = surgeryServiceV2.getVitalSignsList(template);
jsonObject.put("vitalSignsList", vitalSignsList); jsonObject.put("vitalSignsList", vitalSignsList);
// 标记信息 // 标记信息
@ -161,7 +150,7 @@ public class VitalSignTimerV2 {
// 定时任务设置1秒 // 定时任务设置1秒
Timer timer = new Timer(); Timer timer = new Timer();
timer.schedule(timerTask, 0, 2000); timer.schedule(timerTask, 0, 1000);
timerTaskMap.put(sessionId, timerTask); timerTaskMap.put(sessionId, timerTask);
} }
@ -172,8 +161,8 @@ public class VitalSignTimerV2 {
if (masterControlMap.containsKey(database) && masterControlMap.get(database).equals(username)) { if (masterControlMap.containsKey(database) && masterControlMap.get(database).equals(username)) {
// 给药到unity // 给药到unity
WebSocketSession unitySession = aiMedicineTimer.getUnitySession(database); WebSocketSession unitySession = aiMedicineTimer.getUnitySession(database);
result.put("medicine",medicine); result.put("medicine", medicine);
result.put("value",value); result.put("value", value);
result.put("flag", flag); result.put("flag", flag);
result.put("msgType", "addMedicine"); result.put("msgType", "addMedicine");
unitySession.sendMessage(new TextMessage(result.toJSONString().getBytes())); unitySession.sendMessage(new TextMessage(result.toJSONString().getBytes()));

View File

@ -116,8 +116,8 @@ spring:
port: 16373 port: 16373
password: rax137839 password: rax137839
connect-timeout: 5000 connect-timeout: 5000
# database: 0 # 二期 database: 0 # 二期
database: 1 # 一期 # database: 1 # 一期
# 数据库相关配置 # 数据库相关配置
datasource: datasource:
@ -125,13 +125,13 @@ spring:
username: root username: root
password: Xg137839 password: Xg137839
# 一期 # 一期
url: jdbc:mysql://110.41.142.124:3306/rax_backend1?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true # url: jdbc:mysql://110.41.142.124:3306/rax_backend1?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true
# 二期 # 二期
# 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 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
server: server:
port: 6679 #一期 # port: 6679 #一期
# port: 6379 #二期 port: 6379 #二期
servlet: servlet:
context-path: /admin context-path: /admin
@ -165,7 +165,7 @@ spring:
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
username: root username: root
password: root password: root
url: jdbc:mysql://localhost:3306/rax_backend1?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true # 一期 url: jdbc:mysql://110.41.142.124:3306/rax_backend1?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true # 一期
# url: jdbc:mysql://localhost:3306/rax_backend?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true # 二期 # url: jdbc:mysql://localhost:3306/rax_backend?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true # 二期
server: server:

View File

@ -5,6 +5,8 @@ import org.junit.jupiter.api.Test;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
@ -16,11 +18,16 @@ public class Test111 {
@Test @Test
public void test() { public void test() {
String url = "http://127.0.0.1:8080/upms/upms-biz/user/login?token=1"; // String url = "http://127.0.0.1:8080/upms/upms-biz/user/login?token=1";
Map params = GetHttpParamUtil.getParams(url); // Map params = GetHttpParamUtil.getParams(url);
String token = (String) params.get("token"); // String token = (String) params.get("token");
System.out.println("params = " + params); // System.out.println("params = " + params);
System.out.println("token = " + token); // System.out.println("token = " + token);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> subList = list.subList(0, 5);
System.out.println("subList = " + subList);
} }
@Test @Test