add: 配合前端修改的折线图. redis, 推送数据为, 每次发生变化的数值(featuretable)

This commit is contained in:
republicline 2024-10-17 17:32:56 +08:00
parent 92550879f8
commit 98a33d5649
10 changed files with 151 additions and 204 deletions

View File

@ -60,22 +60,23 @@ public class ChatHandler implements WebSocketHandler {
dbNameSessionList.put(dbName, sessionArrayList);
sessionDbMap.put(session.getId(), dbName);
}
dbNameSessionList.get(dbName).add(session);
List<WebSocketSession> webSocketSessions = dbNameSessionList.get(dbName);
webSocketSessions.add(session);
} else {
System.out.println("收到消息-start = " + jsonObject.toJSONString());
String patientName = jsonObject.getString("patientName");
String idNum = jsonObject.getString("idNum");
String date = jsonObject.getString("date");
// 消息内容
String msg = jsonObject.getString("msg");
//
List<WebSocketSession> webSocketSessions = dbNameSessionList.get(idNum);
for (WebSocketSession webSocketSession : webSocketSessions) {
System.out.println("webSocketSession.size() = " + webSocketSessions.size());
System.out.println("webSocketSession = " + webSocketSession);
}
chatService.sendMessageMysql(username, patientName, idNum, date, 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()));
}
}

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

@ -6,13 +6,8 @@ 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, List<WebSocketSession> webSocketSessions) throws Exception;
void stopTimerTask(String simpSessionId);
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

@ -33,31 +33,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}")
@ -71,117 +55,33 @@ 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, List<WebSocketSession> webSocketSessionList) throws SQLException, IOException {
CustomDataSource dataSource = datasourceMap.get(session.getId());
String databaseName = idNum;
System.out.println("databaseName = " + databaseName);
ArrayList<Map> history = new ArrayList<>();
// 获取连接
if (dataSource == null) {
dataSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, databaseName);
boolean status = dataSource.open();
System.out.println("status = " + status);
// 查询历史消息
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);
}
}
// 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);
// }
// }
Connection connection = dataSource.getConnection();
DatabaseMetaData metaData = connection.getMetaData();
String tableName = "t_chat";
@ -206,6 +106,23 @@ public class ChatServiceImpl implements ChatService {
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
Statement statement = connection.createStatement();
String createSql = "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(createSql);
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
JSONObject jsonObject = new JSONObject();
@ -222,54 +139,39 @@ public class ChatServiceImpl implements ChatService {
}
}
// 发消息, 入库
if (StringUtils.hasText(msg)) {
JSONObject param = new JSONObject();
String now = DateUtil.now();
JSONObject param = new JSONObject();
param.put("msgType", "msg");
param.put("createName", username);
param.put("createUser", username);
param.put("createTime", now);
param.put("content", msg);
// 广播消息
for (WebSocketSession webSocketSession : webSocketSessionList) {
webSocketSession.sendMessage(new TextMessage(param.toJSONString().getBytes()));
}
// 入库
Connection connection = dataSource.getConnection();
DatabaseMetaData metaData = connection.getMetaData();
String tableName = "t_chat";
ResultSet tablesx = metaData.getTables(null, null, tableName, new String[]{"TABLE"});
if (!tablesx.next()) {
try {
Statement statement = connection.createStatement();
String sql = "CREATE TABLE `t_chat` (\n" +
" `id` int NOT NULL AUTO_INCREMENT,\n" +
" `content` varchar(5000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `create_time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `create_user` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `create_name` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,\n" +
" `deleted` bit(1) NULL DEFAULT NULL,\n" +
" `revoked` bit(1) NULL DEFAULT NULL,\n" +
" PRIMARY KEY (`id`) USING BTREE\n" +
") ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;";
statement.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement("INSERT INTO t_chat (content, create_time, create_user, create_name, deleted, revoked) VALUES (?, ?, ?, ?, ?, ?)");
preparedStatement.setString(1, msg);
param.put("content", msg);
String now = DateUtil.now();
preparedStatement.setString(2, now);
param.put("createTime", now);
preparedStatement.setString(3, username);
param.put("createUser", username);
// String name = sysUser.getName();
preparedStatement.setString(4, username);
param.put("createName", username);
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();
@ -279,20 +181,9 @@ public class ChatServiceImpl implements ChatService {
// e.printStackTrace();
// }
// }
for (WebSocketSession webSocketSession : webSocketSessionList) {
webSocketSession.sendMessage(new TextMessage(param.toJSONString().getBytes()));
}
}
}
@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) {
@ -301,14 +192,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;
/**
* 生命体征数据
@ -64,6 +66,10 @@ public class VitalSignServiceImpl implements VitalSignsService {
@Value("${vital-sign.mysql.username}")
private String mysqlUsername;
@Autowired
private RedisTemplate redisTemplate;
/**
* 获取生命体征最新一条数据
*
@ -96,15 +102,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,12 +185,13 @@ 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.open();

View File

@ -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);

View File

@ -180,7 +180,8 @@ public class VitalSignTimerWS {
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

@ -100,7 +100,7 @@ mybatis-plus:
jdbc-type-for-null: 'null'
call-setters-on-nulls: true
shrink-whitespaces-in-sql: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
---
spring:

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