Compare commits

...

10 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
39 changed files with 1195 additions and 552 deletions

View File

@ -2,6 +2,7 @@ package com.rax.auth.endpoint;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.rax.common.core.constant.CacheConstants;
import com.rax.common.core.constant.SecurityConstants;
import com.rax.common.security.annotation.Inner;
@ -43,6 +44,7 @@ public class ImageCodeEndpoint {
@SneakyThrows
@GetMapping("/image")
public void image(String randomStr, HttpServletResponse response) {
System.out.println("randomStr = " + randomStr);
ArithmeticCaptcha captcha = new ArithmeticCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);
String result = captcha.text();
@ -55,7 +57,10 @@ public class ImageCodeEndpoint {
@SneakyThrows
@GetMapping("/textImage")
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();
redisTemplate.opsForValue().set(CacheConstants.DEFAULT_CODE_KEY + randomStr, code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
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.data.redis.connection.RedisConnectionFactory;
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.StringRedisSerializer;
/**
* @author lengleng
@ -23,11 +25,12 @@ public class RedisTemplateConfiguration {
@Primary
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
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.setKeySerializer(new StringRedisSerializer());
// redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}

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.ZoneId;
import java.time.format.DateTimeFormatter;
@ -12,13 +14,19 @@ import java.util.Date;
*/
public class DBNameTest {
public static void main(String[] args) {
String patientName = DatabaseNameUtil.encrypt("eee");
String idNum = DatabaseNameUtil.encrypt("10");
System.out.println("DBName = " + patientName + "_" + idNum);
//String patientName = DatabaseNameUtil.encrypt("eee");
//String idNum = DatabaseNameUtil.encrypt("10");
//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 date = getDate(new Date(), 10);
System.out.println("date = " + date);
String decrypt = DatabaseNameUtil.decrypt("Qw==");
System.out.println("decrypt = " + decrypt);
}
public static String getDate(Date now, int days){

View File

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

View File

@ -8,7 +8,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rax.admin.api.dto.HospitalDTO;
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.service.SysHospitalService;
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.entity.SysLog;
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.SysUserMapper;
import com.rax.admin.service.SysLogService;
@ -66,7 +66,7 @@ public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> impleme
.le(SysLog::getCreateTime, lastDayOfMonth)
.eq(sysLog.getLogType() != null, SysLog::getLogType, sysLog.getLogType())
.orderByDesc(SysLog::getCreateTime).list();
}else {
} else {
list = this.lambdaQuery()
.eq(SysLog::getHospitalId, currentHospital)
.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());
SysUser sysUser = sysUserMapper.selectOne(userLambdaQueryWrapper);
// 设置到日志对象中
if (sysUser != null) {
sysLog.setHospitalId(sysUser.getHospitalId());
}else {
return Boolean.FALSE;
}
}
baseMapper.insert(sysLog);
return Boolean.TRUE;

View File

@ -17,15 +17,15 @@ import org.springframework.stereotype.Component;
@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) {
}
}
//String connectionString = "mongodb://localhost:27017";
//MongoClient mongoClient = MongoClients.create(connectionString);
//
//
//
//public void backup() {
// MongoIterable<String> DbNames = mongoClient.listDatabaseNames();
// for (String dbName : DbNames) {
//
// }
//}
}

View File

@ -1,10 +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;
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.util.RedisUtils;
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;
public MongoDBSource(String host, String password, String username, String database) {
this.host = host;
this.password = password;
this.username = username;
private static final String MONGO_CONNECTION_URL =
"mongodb://useradmin:Xg137839mg@110.41.142.124:27017/?directConnection=true";
public MongoDBSource(String database) {
this.host = "110.41.142.124:27017";
this.password = "Xg137839mg";
this.username = "useradmin";
this.database = database;
}

View File

@ -35,12 +35,12 @@ public class MySQLSource extends CustomDataSource {
this.database = database;
}
@SneakyThrows
public boolean open() {
boolean status = true;
try {
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.setUsername(this.username);
dataSource.setPassword(this.password);

View File

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

View File

@ -12,10 +12,10 @@ import java.util.HashMap;
import java.util.Map;
/**
* project_name: remote-control-backend
* time: 2024/9/4 14:56
* author: republicline
* description:
* @project_name: remote-control-backend
* @time: 2024/9/4 14:56
* @author: republicline
* @description:
*/
@Component
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.web.socket.WebSocketHandler;
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.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;
@ -22,10 +23,10 @@ public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(medicineHandler(), "/rax/vitalSignsMedicine")
.addHandler(chatHandler(), "/rax/chatRoom")
.addHandler(addMedicineHandler(), "/rax/addMedicine")
.addHandler(machineFeedbackHandler(),"/rax/getMedicine")
.addInterceptors(new HttpSessionHandshakeInterceptor())
.addInterceptors(webSocketInterceptors())
// .addHandler(addMedicineHandler(), "/rax/addMedicine")
// .addHandler(machineFeedbackHandler(),"/rax/getMedicine")
// .addInterceptors(new HttpSessionHandshakeInterceptor())
// .addInterceptors(webSocketInterceptors())
.setAllowedOrigins("*");
}
@ -39,15 +40,15 @@ public class WebSocketConfig implements WebSocketConfigurer {
return new ChatHandler();
}
@Bean
public WebSocketHandler addMedicineHandler() {
return new AddMedicineHandler();
}
// @Bean
// public WebSocketHandler addMedicineHandler() {
// return new AddMedicineHandler();
// }
@Bean
public WebSocketHandler machineFeedbackHandler() {
return new MachineFeedbackHandler();
}
// @Bean
// public WebSocketHandler machineFeedbackHandler() {
// return new MachineFeedbackHandler();
// }
@Bean
public HandshakeInterceptor webSocketInterceptors() {

View File

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

View File

@ -1,20 +1,29 @@
package com.rax.vital.v1.handler;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
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.v1.medicine.service.ChatService;
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.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;
public class ChatHandler implements WebSocketHandler {
@Resource
@ -23,8 +32,31 @@ public class ChatHandler implements WebSocketHandler {
@Resource
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();
// dbName -> sessionList
private Map<String, List<WebSocketSession>> dbNameSessionList = new ConcurrentHashMap();
// sessionId -> dbName
private Map<String, String> sessionDbMap = new ConcurrentHashMap();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
startHeartbeat(session);
@ -32,7 +64,8 @@ public class ChatHandler implements WebSocketHandler {
@Override
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);
String token = (String) params.get("token");
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
@ -41,30 +74,89 @@ public class ChatHandler implements WebSocketHandler {
String payload = (String) message.getPayload();
JSONObject jsonObject = JSONObject.parseObject(payload);
if ("heartbeat".equals(jsonObject.getString("msgType"))) {
// session.sendMessage(new TextMessage(""));
} else {
String patientName = jsonObject.getString("patientName");
String idNum = jsonObject.getString("idNum");
String date = jsonObject.getString("date");
// 消息内容
String msg = jsonObject.getString("msg");
chatService.sendMessageMysql(username, patientName, idNum, date, session, msg);
} else if ("init".equals(jsonObject.getString("msgType"))) {
// 初始化, 将session信息保存起来
String dbName = 'a' + jsonObject.getString("idNum");
// 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 content = jsonObject.getString("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
public void handleTransportError(WebSocketSession session, Throwable exception) {
System.out.println("Error: " + exception.getMessage());
stopMap(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
System.out.println("CloseStatus: " + closeStatus.getReason() + closeStatus.getCode());
stopHeartbeat(session);
chatService.stopTask(session.getId());
//chatService.stopTask(session.getId());
stopMap(session);
}
@Override
@ -83,7 +175,7 @@ public class ChatHandler implements WebSocketHandler {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else {
stopHeartbeat(session);
chatService.stopTask(session.getId());
//chatService.stopTask(session.getId());
session.close();
}
} catch (Exception e) {
@ -100,4 +192,117 @@ public class ChatHandler implements WebSocketHandler {
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.v1.timer.VitalSignTimerWS;
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.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
@ -12,9 +13,6 @@ import org.springframework.web.socket.*;
import java.net.URLDecoder;
import java.util.Map;
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 {
@ -24,11 +22,13 @@ public class MedicineHandler implements WebSocketHandler {
@Resource
private OAuth2AuthorizationService authorizationService;
private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap();
private Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap();
@Override
public void afterConnectionEstablished(WebSocketSession session) {
startHeartbeat(session);
sessionMap.put(session.getId(), session);
}
@Override
@ -45,23 +45,24 @@ public class MedicineHandler implements WebSocketHandler {
if ("heartbeat".equals(jsonObject.getString("msgType"))) {
// session.sendMessage(new TextMessage(""));
} else {
String patientName = jsonObject.getString("patientName");
// String patientName = jsonObject.getString("patientName");
String idNum = jsonObject.getString("idNum");
String databaseName = idNum;
String databaseName = 'a' + idNum;
vitalSignTimerWS.createAndSendMessageMySQL(databaseName, username, session);
}
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) {
sessionMap.remove(session.getId());
System.out.println("Error: " + exception.getMessage());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
System.out.println("MedicineHandler Connection closed:" + closeStatus.getReason());
stopHeartbeat(session);
vitalSignTimerWS.stopTimerTask(session.getId());
// stopHeartbeat(session);
sessionMap.remove(session.getId());
}
@Override
@ -69,32 +70,24 @@ public class MedicineHandler implements WebSocketHandler {
return false;
}
private void startHeartbeat(WebSocketSession session) {
if (!timerTaskMap.containsKey(session.getId())) {
ScheduledExecutorService heartbeatExecutor = Executors.newScheduledThreadPool(1);
heartbeatExecutor.scheduleAtFixedRate(() -> {
try {
@Scheduled(fixedRate = 30000)
private void sendHeartbeat() {
for (WebSocketSession session : sessionMap.values()) {
if (session.isOpen()) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msgType", "heartbeat");
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else {
session.close();
stopHeartbeat(session);
vitalSignTimerWS.stopTimerTask(session.getId());
}
} catch (Exception e) {
e.printStackTrace();
stopHeartbeat(session);
}
}, 0, 10, TimeUnit.SECONDS);
timerTaskMap.put(session.getId(), heartbeatExecutor);
}else {
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 msg = params.getString("msg");
chatService.sendMessage(username, patientName, idNum, date, simpSessionId, msg);
//chatService.sendMessage(username, patientName, idNum, date, simpSessionId, msg);
} else {
throw new AccessDeniedException("Access is denied");
}

View File

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

View File

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

View File

@ -25,7 +25,7 @@ public interface VitalSignsService {
*
* @return
*/
List<Map> getVitalSignsList(Connection connection);
Map getVitalSignsList(Connection connection,String username, String dbName);
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.data.mongodb.core.MongoTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;
@ -25,6 +26,7 @@ import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ -32,29 +34,15 @@ import java.util.concurrent.ConcurrentHashMap;
@Service
public class ChatServiceImpl implements ChatService {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@Autowired
private SysUserService SysUserService;
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, 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;
//
// private static final Map<String, Map<String, WebSocketSession>> databaseSessionMap = new ConcurrentHashMap<>();
//
// private static final Map<String, String> sessionDatabaseMap = new ConcurrentHashMap<>();
// mysql地址
@Value("${vital-sign.mysql.host}")
@ -68,215 +56,66 @@ public class ChatServiceImpl implements ChatService {
@Value("${vital-sign.mysql.password}")
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
public void sendMessage(String username, String patientName, String idNum, String date, WebSocketSession session, String msg) throws IOException {
CustomDataSource mongoDBSource = datasourceMap.get(session.getId());
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) {
@Async
public void sendMessageMysql(String username, String patientName, String idNum, String msgType, WebSocketSession session, String msg, List<WebSocketSession> webSocketSessionList) throws SQLException, IOException {
CustomDataSource dataSource = datasourceMap.get(session.getId());
// String databaseName = patientName + idNum;
String databaseName = idNum;
ArrayList<Map> history = new ArrayList<>();
if (dataSource == null) {
dataSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, databaseName);
dataSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, idNum);
boolean status = dataSource.open();
if (status) {
datasourceMap.put(session.getId(), dataSource);
sessionDatabaseMap.put(session.getId(), databaseName);
Map<String, WebSocketSession> sessionMap = databaseSessionMap.get(databaseName);
if (sessionMap == null) {
sessionMap = new HashMap();
sessionMap.put(session.getId(), session);
databaseSessionMap.put(databaseName, sessionMap);
} else {
if (!sessionMap.containsKey(session.getId())) {
sessionMap.put(session.getId(), session);
}
}
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 {
}else {
JSONObject jsonObject = new JSONObject();
jsonObject.put("status", 1);
jsonObject.put("msg", "数据库未创建, 请重新连接。");
jsonObject.put("msgType", "msg");
try {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
session.close();
} catch (IOException e) {
e.printStackTrace();
}
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 {
Statement statement = connection.createStatement();
String sql = "CREATE TABLE `t_chat` (\n" +
" `id` int NOT NULL AUTO_INCREMENT,\n" +
" `content` varchar(5000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `create_time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `create_user` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `create_name` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `deleted` bit(1) NULL DEFAULT NULL,\n" +
" `revoked` bit(1) NULL DEFAULT NULL,\n" +
" PRIMARY KEY (`id`) USING BTREE\n" +
") ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;";
statement.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
// 发消息, 入库
if (StringUtils.hasText(msg)) {
String now = DateUtil.now();
JSONObject param = new JSONObject();
param.put("msgType", msgType);
param.put("createUser", username);
param.put("createTime", now);
param.put("content", msg);
//System.out.println("param = " + param);
//System.out.println("webSocketSessionList = " + webSocketSessionList);
// 广播消息
for (WebSocketSession webSocketSession : webSocketSessionList) {
webSocketSession.sendMessage(new TextMessage(param.toJSONString().getBytes()));
}
// 入库
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = null;
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);
param.put("content", msg);
String now = DateUtil.now();
preparedStatement.setString(2, now);
param.put("createTime", now);
preparedStatement.setString(3, username);
param.put("createUser", username);
String name = sysUser.getName();
preparedStatement.setString(4, name);
param.put("createName", name);
// String name = sysUser.getName();
preparedStatement.setString(4, msgType);
preparedStatement.setInt(5, 0);
preparedStatement.setInt(6, 0);
param.put("msgType", "msg");
preparedStatement.execute();
} catch (SQLException e) {
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
public synchronized void stopTask(String simpSessionId) {
@ -285,14 +124,14 @@ public class ChatServiceImpl implements ChatService {
mongoDBSource.close();
datasourceMap.remove(simpSessionId);
}
String databaseName = sessionDatabaseMap.get(simpSessionId);
if (databaseName != null) {
sessionDatabaseMap.remove(simpSessionId);
Map<String, WebSocketSession> stringWebSocketSessionMap = databaseSessionMap.get(databaseName);
stringWebSocketSessionMap.remove(simpSessionId);
if (stringWebSocketSessionMap.isEmpty()) {
databaseSessionMap.remove(databaseName);
}
}
// String databaseName = sessionDatabaseMap.get(simpSessionId);
// if (databaseName != null) {
// sessionDatabaseMap.remove(simpSessionId);
// Map<String, WebSocketSession> stringWebSocketSessionMap = databaseSessionMap.get(databaseName);
// stringWebSocketSessionMap.remove(simpSessionId);
// if (stringWebSocketSessionMap.isEmpty()) {
// databaseSessionMap.remove(databaseName);
// }
// }
}
}

View File

@ -7,12 +7,14 @@ import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoIterable;
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.MySQLSource;
import com.rax.vital.common.util.DatabaseNameUtil;
import com.rax.vital.v1.medicine.service.VitalSignsService;
import lombok.extern.slf4j.Slf4j;
import org.bson.BsonRegularExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
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.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* 生命体征数据
@ -38,20 +40,6 @@ import java.util.Map;
@RefreshScope
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}")
private String informationDatabase;
@ -64,6 +52,10 @@ public class VitalSignServiceImpl implements VitalSignsService {
@Value("${vital-sign.mysql.username}")
private String mysqlUsername;
@Autowired
private RedisTemplate redisTemplate;
/**
* 获取生命体征最新一条数据
*
@ -96,15 +88,60 @@ public class VitalSignServiceImpl implements VitalSignsService {
}
@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<>();
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` " +
" GROUP BY Phase, BIS, HR, SBP, DBP, ST, TEMP, SPO2, EtCO2, PPG, ABG, TOF, Time " +
" ORDER BY time DESC LIMIT 10;";
ResultSet resultSet = statement.executeQuery(sql);
// " GROUP BY Phase, BIS, HR, SBP, DBP, ST, TEMP, SPO2, EtCO2, PPG, ABG, TOF, Time " +
" ORDER BY id DESC LIMIT 20;";
PreparedStatement statement = connection.prepareStatement(sql2);
ResultSet resultSet = statement.executeQuery(sql2);
while (resultSet.next()) {
Map<String, Object> vital = new HashMap();
vital.put("Phase", resultSet.getString("Phase"));
@ -134,14 +171,15 @@ public class VitalSignServiceImpl implements VitalSignsService {
vital.put("EtCO2_except", etCO2 <= 30 || etCO2 >= 45);
vitalList.add(vital);
}
return vitalList;
} catch (SQLException e) {
throw new RuntimeException(e);
}
return vitalList;
}
public R getPatientInfo(String databaseName) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName);
MongoDBSource mongoDBSource = new MongoDBSource(databaseName);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query();
@ -183,25 +221,25 @@ public class VitalSignServiceImpl implements VitalSignsService {
} catch (SQLException e) {
e.printStackTrace();
}
mySQLSource.close();
return R.ok(map);
}
@Override
public R getDatabaseList() {
MongoClientSettings.Builder mongoBuilder = MongoClientSettings.builder();
// mongodb://账户:密码@ip:端口/?authSource=admin
String connectionUrl = "mongodb://" + mongoUsername + ":" + mongoPassword + "@" + mongoDBHost + "/" + "?authSource=admin";
mongoBuilder.applyConnectionString(new ConnectionString(connectionUrl));
MongoClient mongoClient = MongoClients.create(mongoBuilder.build(), SpringDataMongoDB.driverInformation());
MongoIterable<String> databaseNames = mongoClient.listDatabaseNames();
for (String database : databaseNames) {
}
//MongoClientSettings.Builder mongoBuilder = MongoClientSettings.builder();
//// mongodb://账户:密码@ip:端口/?authSource=admin
//String connectionUrl = "mongodb://" + mongoUsername + ":" + mongoPassword + "@" + mongoDBHost + "/" + "?authSource=admin";
//mongoBuilder.applyConnectionString(new ConnectionString(connectionUrl));
//MongoClient mongoClient = MongoClients.create(mongoBuilder.build(), SpringDataMongoDB.driverInformation());
//MongoIterable<String> databaseNames = mongoClient.listDatabaseNames();
//for (String database : databaseNames) {
//}
return null;
}
public Page getPatientPage(String name, String dept, long offset, int limit) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query();
@ -231,7 +269,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
@Override
public List getSurgeryCount(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>();
@ -270,7 +308,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
}
public List getSurgeryDuration(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>();
@ -319,7 +357,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
}
public List getSurgeryTypeProportion(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>();
@ -339,7 +377,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
}
public List getSurgeryOtherDuration(String start, String end) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
List<AggregationOperation> operations = new ArrayList<>();
@ -387,7 +425,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
@Override
public List getPatientSurgeryList(String name, String code, String surgery, String type) {
if (StringUtils.hasText(code)) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
@ -437,7 +475,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
public List getSurgeryTableData(String name, String code, String date, String table) {
if (StringUtils.hasText(code)) {
if (!StringUtils.hasText(name)) {
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, informationDatabase);
MongoDBSource mongoDBSource = new MongoDBSource(informationDatabase);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query();
@ -452,7 +490,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
mongoDBSource.close();
}
String database = DatabaseNameUtil.encrypt(name) + "_" + DatabaseNameUtil.encrypt(code) + "_" + date;
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database);
MongoDBSource mongoDBSource = new MongoDBSource(database);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
Query query = new Query();

View File

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

View File

@ -99,7 +99,7 @@ public class VitalSignTimerWS {
CustomDataSource dataSource = dataSourceMap.get(sessionId);
if (dataSource == null) {
dataSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database);
dataSource = new MongoDBSource(database);
dataSourceMap.put(sessionId, dataSource);
dataSource.open();
}
@ -139,11 +139,11 @@ public class VitalSignTimerWS {
}
public void createAndSendMessageMySQL(String database, String username, WebSocketSession session) {
synchronized (username) {
// synchronized (username) {
if (!masterControlMap.containsKey(database)) {
masterControlMap.put(database, username);
}
}
// }
String sessionId = session.getId();
@ -177,10 +177,10 @@ public class VitalSignTimerWS {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
Connection connection = finalDataSource.getConnection();
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);
List<Map> aiMedicineList = aiMedicineService.getAIMedicine(connection);
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.TokenUtil;
import com.rax.vital.v2.timer.AIMedicineTimer;
import com.rax.vital.v2.timer.HeartBeatTimer;
import com.rax.vital.v2.timer.VitalSignTimerV2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@ -40,16 +41,16 @@ public class AddMedicineHandler implements WebSocketHandler {
@Autowired
private AIMedicineTimer aiMedicineTimer;
// 发送心跳任务的定时任务容器
private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap<>();
@Autowired
private HeartBeatTimer heartBeatTimer;
private String SERVICE_NAME = HeartBeatTimer.addMedicineHandler;
@Override
public void afterConnectionEstablished(WebSocketSession session) {
startHeartbeat(session);
heartBeatTimer.putSession(SERVICE_NAME,session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
@ -124,7 +125,7 @@ public class AddMedicineHandler implements WebSocketHandler {
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) {
stopHeartbeat(session);
heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session);
SysLog sysLog = sysLoggerBuilder.buildSysLog("给药接口异常中断:"+exception.getMessage(), "4", session);
sysLogService.saveLog(sysLog);
@ -132,7 +133,8 @@ public class AddMedicineHandler implements WebSocketHandler {
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
stopHeartbeat(session);
//stopHeartbeat(session);
heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session);
SysLog sysLog = sysLoggerBuilder.buildSysLog("给药接口客户端,断开连接", "0", session);
sysLogService.saveLog(sysLog);
@ -143,33 +145,6 @@ public class AddMedicineHandler implements WebSocketHandler {
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) {
@ -178,12 +153,12 @@ public class AddMedicineHandler implements WebSocketHandler {
if (session.isOpen()) {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
}else {
stopHeartbeat(session);
heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session);
session.close();
}
}catch (Exception e) {
stopHeartbeat(session);
heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session);
log.error("addMedicineHandler-sendMsgAsync error: {}", e.getMessage());
}

View File

@ -1,23 +1,28 @@
package com.rax.vital.v2.handler;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.rax.admin.api.entity.SysLog;
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.GetHttpParamUtil;
import com.rax.vital.common.util.SysLoggerBuilder;
import com.rax.vital.common.util.TokenUtil;
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.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;
@Component
public class ChatHandler implements WebSocketHandler {
@ -34,11 +39,24 @@ public class ChatHandler implements WebSocketHandler {
@Autowired
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
public void afterConnectionEstablished(WebSocketSession session) {
startHeartbeat(session);
heartBeatTimer.putSession(SERVICE_NAME, session);
}
@Override
@ -47,34 +65,66 @@ public class ChatHandler implements WebSocketHandler {
String payload = (String) message.getPayload();
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 token = GetHttpParamUtil.getParam(query, "token");
Map<String, Object> map = tokenUtil.parseToken(token);
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 databaseName = DatabaseNameUtil.encrypt(patientName) + "_" + DatabaseNameUtil.encrypt(idNum) + "_" + date;
chatService.sendMessage(databaseName, username, session, msg);
String content = jsonObject.getString("content");
List<WebSocketSession> webSocketSessions = dbNameSessionList.get(databaseName);
// 转发消息
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
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);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
stopHeartbeat(session);
heartBeatTimer.removeSession(session);
chatService.stopTask(session.getId());
SysLog sysLog = sysLoggerBuilder.buildSysLog("聊天室接口关闭", "0", session);
sysLogService.saveLog(sysLog);
@ -85,31 +135,18 @@ public class ChatHandler implements WebSocketHandler {
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);
chatService.stopTask(session.getId());
session.close();
}
} catch (Exception e) {
e.printStackTrace();
stopHeartbeat(session);
}
}, 0, 10, TimeUnit.SECONDS);
timerTaskMap.put(session.getId(), heartbeatExecutor);
}
// 入库mongodb
private void insertCollection(String dbName, JSONObject jsonObject) {
MongoDBSource mongoDBSource = new MongoDBSource(dbName);
mongoDBSource.open();
MongoTemplate mongoTemplate = mongoDBSource.getConnection();
Document document = new Document();
document.put("msgType", jsonObject.getString("msgType"));
document.put("createUser", jsonObject.getString("createUser"));
document.put("createTime", jsonObject.getString("createTime"));
document.put("content", jsonObject.getString("content"));
mongoTemplate.insert(jsonObject, "t_chat");
mongoDBSource.close();
}
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.SysLoggerBuilder;
import com.rax.vital.v2.timer.AIMedicineTimer;
import com.rax.vital.v2.timer.HeartBeatTimer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@ -35,13 +36,19 @@ public class MachineFeedbackHandler implements WebSocketHandler {
@Autowired
private AIMedicineTimer aiMedicineTimer;
@Autowired
private HeartBeatTimer heartBeatTimer;
private String SERVICE_NAME = HeartBeatTimer.machineFeedbackHandler;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws IOException {
JSONObject msg = new JSONObject();
msg.put("msgType", "msg");
msg.put("msg", "已成功连接服务器!");
session.sendMessage(new TextMessage(msg.toJSONString().getBytes()));
startHeartbeat(session);
heartBeatTimer.putSession(SERVICE_NAME,session);
}
@Override
@ -141,7 +148,7 @@ public class MachineFeedbackHandler implements WebSocketHandler {
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) {
stopHeartbeat(session);
heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session);
SysLog sysLog = sysLoggerBuilder.buildSysLog("仪器端获取收药口异常中断", "4", session);
sysLogService.saveLog(sysLog);
@ -149,7 +156,7 @@ public class MachineFeedbackHandler implements WebSocketHandler {
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
stopHeartbeat(session);
heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session);
SysLog sysLog = sysLoggerBuilder.buildSysLog("仪器端收药接口关闭", "0", session);
sysLogService.saveLog(sysLog);
@ -160,33 +167,6 @@ public class MachineFeedbackHandler implements WebSocketHandler {
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) {
@ -195,12 +175,12 @@ public class MachineFeedbackHandler implements WebSocketHandler {
if (session.isOpen()) {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else {
stopHeartbeat(session);
heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session);
session.close();
}
} catch (Exception e) {
stopHeartbeat(session);
heartBeatTimer.removeSession(session);
aiMedicineTimer.closeConnection(session);
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.SysLoggerBuilder;
import com.rax.vital.common.util.TokenUtil;
import com.rax.vital.v2.timer.HeartBeatTimer;
import com.rax.vital.v2.timer.VitalSignTimerV2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@ -39,11 +40,17 @@ public class MedicineHandler implements WebSocketHandler {
@Autowired
private TokenUtil tokenUtil;
private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap<>();
// 全局心跳任务容器
@Autowired
private HeartBeatTimer heartBeatTimer;
private String SERVICE_NAME = HeartBeatTimer.medicineHandler;
@Override
public void afterConnectionEstablished(WebSocketSession session) {
startHeartbeat(session);
heartBeatTimer.putSession(SERVICE_NAME,session);
}
@Override
@ -70,7 +77,7 @@ public class MedicineHandler implements WebSocketHandler {
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
stopHeartbeat(session);
heartBeatTimer.removeSession(session);
vitalSignTimerV2.stopTimerTask(session.getId());
SysLog sysLog = sysLoggerBuilder.buildSysLog("生命体征接口异常中断", "4", session);
sysLogService.saveLog(sysLog);
@ -78,7 +85,7 @@ public class MedicineHandler implements WebSocketHandler {
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
stopHeartbeat(session);
heartBeatTimer.removeSession(session);
vitalSignTimerV2.stopTimerTask(session.getId());
SysLog sysLog = sysLoggerBuilder.buildSysLog("生命体征接口连接关闭", "0", session);
sysLogService.saveLog(sysLog);
@ -89,31 +96,4 @@ public class MedicineHandler implements WebSocketHandler {
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

@ -37,36 +37,11 @@ public class ChatServiceImpl implements ChatService {
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
public void sendMessage(String databaseName, String username, WebSocketSession session, String msg) throws IOException {
CustomDataSource mongoDBSource = datasourceMap.get(session.getId());
if (mongoDBSource == null) {
mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, databaseName);
mongoDBSource = new MongoDBSource(databaseName);
mongoDBSource.open();
datasourceMap.put(session.getId(), mongoDBSource);
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;
MongoDBSource mongoDBSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database);
MongoDBSource mongoDBSource = new MongoDBSource(database);
mongoDBSource.open();
MongoTemplate template = mongoDBSource.getConnection();
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
@RequiredArgsConstructor
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;
@ -77,7 +66,7 @@ public class VitalSignTimerV2 {
CustomDataSource dataSource = dataSourceMap.get(sessionId);
if (dataSource == null) {
dataSource = new MongoDBSource(mongoDBHost, mongoPassword, mongoUsername, database);
dataSource = new MongoDBSource(database);
dataSourceMap.put(sessionId, dataSource);
dataSource.open();
}
@ -88,8 +77,8 @@ public class VitalSignTimerV2 {
MongoTemplate template = finalMongoDBSource.getConnection();
JSONObject jsonObject = new JSONObject();
// 生命体征信息
List vitalSignsList = surgeryServiceV2.getVitalSignsList(template);
// 生命体征信息 这里要改改
List<Map> vitalSignsList = surgeryServiceV2.getVitalSignsList(template);
jsonObject.put("vitalSignsList", vitalSignsList);
// 标记信息
@ -161,7 +150,7 @@ public class VitalSignTimerV2 {
// 定时任务设置1秒
Timer timer = new Timer();
timer.schedule(timerTask, 0, 2000);
timer.schedule(timerTask, 0, 1000);
timerTaskMap.put(sessionId, timerTask);
}
@ -172,8 +161,8 @@ public class VitalSignTimerV2 {
if (masterControlMap.containsKey(database) && masterControlMap.get(database).equals(username)) {
// 给药到unity
WebSocketSession unitySession = aiMedicineTimer.getUnitySession(database);
result.put("medicine",medicine);
result.put("value",value);
result.put("medicine", medicine);
result.put("value", value);
result.put("flag", flag);
result.put("msgType", "addMedicine");
unitySession.sendMessage(new TextMessage(result.toJSONString().getBytes()));

View File

@ -165,7 +165,7 @@ spring:
driver-class-name: com.mysql.cj.jdbc.Driver
username: 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 # 二期
server:

View File

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