add: 一期代码

This commit is contained in:
republicline 2024-11-13 13:16:29 +08:00
parent 1e39cc83a8
commit 17be499d6d
11 changed files with 353 additions and 289 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,27 +1,29 @@
package com.rax.vital.v1.handler; package com.rax.vital.v1.handler;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.rax.common.core.util.RedisUtils; import com.rax.vital.common.datasource.CustomDataSource;
import com.rax.vital.common.datasource.MySQLSource;
import com.rax.vital.common.util.GetHttpParamUtil; import com.rax.vital.common.util.GetHttpParamUtil;
import com.rax.vital.v1.medicine.service.ChatService; import com.rax.vital.v1.medicine.service.ChatService;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType; import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.*; import org.springframework.web.socket.*;
import java.io.IOException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ChatHandler implements WebSocketHandler { public class ChatHandler implements WebSocketHandler {
@Resource @Resource
@ -33,6 +35,20 @@ public class ChatHandler implements WebSocketHandler {
@Autowired @Autowired
private RedisTemplate redisTemplate; private RedisTemplate redisTemplate;
// mysql地址
@Value("${vital-sign.mysql.host}")
private String mysqlHost;
// mysql用户名
@Value("${vital-sign.mysql.username}")
private String mysqlUsername;
// mysql用户密码
@Value("${vital-sign.mysql.password}")
private String mysqlPassword;
private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(5);
private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap(); private Map<String, ScheduledExecutorService> timerTaskMap = new ConcurrentHashMap();
// dbName -> sessionList // dbName -> sessionList
@ -55,9 +71,9 @@ public class ChatHandler implements WebSocketHandler {
OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (authorization != null) { if (authorization != null) {
String username = authorization.getPrincipalName(); String username = authorization.getPrincipalName();
String payload = (String) message.getPayload(); String payload = (String) message.getPayload();
JSONObject jsonObject = JSONObject.parseObject(payload); JSONObject jsonObject = JSONObject.parseObject(payload);
if ("heartbeat".equals(jsonObject.getString("msgType"))) { if ("heartbeat".equals(jsonObject.getString("msgType"))) {
// session.sendMessage(new TextMessage("")); // session.sendMessage(new TextMessage(""));
} else if ("init".equals(jsonObject.getString("msgType"))) { } else if ("init".equals(jsonObject.getString("msgType"))) {
@ -79,6 +95,8 @@ public class ChatHandler implements WebSocketHandler {
} }
List<WebSocketSession> webSocketSessions = dbNameSessionList.get(dbName); List<WebSocketSession> webSocketSessions = dbNameSessionList.get(dbName);
webSocketSessions.add(session); webSocketSessions.add(session);
// 创建数据库表
initTChatTable(dbName, session);
// ArrayList<String> sessionIDList = new ArrayList<>(); // ArrayList<String> sessionIDList = new ArrayList<>();
// for (WebSocketSession webSocketSession : webSocketSessions) { // for (WebSocketSession webSocketSession : webSocketSessions) {
// if (webSocketSession.isOpen()) { // if (webSocketSession.isOpen()) {
@ -92,14 +110,31 @@ public class ChatHandler implements WebSocketHandler {
// redisTemplate.expire("chat_" + dbName, 60 * 60, TimeUnit.SECONDS); // redisTemplate.expire("chat_" + dbName, 60 * 60, TimeUnit.SECONDS);
// redisTemplate.opsForHash().putAll("chat_sessionId_" + dbName, sessionDbMap); // redisTemplate.opsForHash().putAll("chat_sessionId_" + dbName, sessionDbMap);
// redisTemplate.expire("chat_" + dbName, 60 * 60, TimeUnit.SECONDS); // redisTemplate.expire("chat_" + dbName, 60 * 60, TimeUnit.SECONDS);
} else { } else if ("msg".equals(jsonObject.getString("msgType")) ||
String patientName = jsonObject.getString("patientName"); "audio".equals(jsonObject.getString("msgType"))) {
//String patientName = jsonObject.getString("patientName");
String dbName = 'a' + jsonObject.getString("idNum"); String dbName = 'a' + jsonObject.getString("idNum");
String date = jsonObject.getString("date"); //String date = jsonObject.getString("date");
String msgType = jsonObject.getString("msgType");
// 消息内容 // 消息内容
String msg = jsonObject.getString("msg"); String content = jsonObject.getString("msg");
List<WebSocketSession> webSocketSessions = dbNameSessionList.get(dbName); List<WebSocketSession> webSocketSessions = dbNameSessionList.get(dbName);
chatService.sendMessageMysql(username, patientName, dbName, date, session, msg, webSocketSessions); // 转发消息
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 { } else {
String msgContent = "token无效,认证失败"; String msgContent = "token无效,认证失败";
@ -120,7 +155,7 @@ public class ChatHandler implements WebSocketHandler {
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
System.out.println("CloseStatus: " + closeStatus.getReason() + closeStatus.getCode()); System.out.println("CloseStatus: " + closeStatus.getReason() + closeStatus.getCode());
stopHeartbeat(session); stopHeartbeat(session);
chatService.stopTask(session.getId()); //chatService.stopTask(session.getId());
stopMap(session); stopMap(session);
} }
@ -140,7 +175,7 @@ public class ChatHandler implements WebSocketHandler {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes())); session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
} else { } else {
stopHeartbeat(session); stopHeartbeat(session);
chatService.stopTask(session.getId()); //chatService.stopTask(session.getId());
session.close(); session.close();
} }
} catch (Exception e) { } catch (Exception e) {
@ -165,4 +200,110 @@ public class ChatHandler implements WebSocketHandler {
sessionDbMap.remove(session.getId()); 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` blob,
`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

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

View File

@ -7,7 +7,7 @@ import java.util.List;
public interface ChatService { public interface ChatService {
void sendMessageMysql(String username, String patientName, String idNum, String date, WebSocketSession session, String msg, List<WebSocketSession> webSocketSessions) throws Exception; void sendMessageMysql(String username, String patientName, String idNum, String msgType, WebSocketSession session, String msg, List<WebSocketSession> webSocketSessions) throws Exception;
void stopTask(String simpSessionId); void stopTask(String simpSessionId);
} }

View File

@ -59,135 +59,60 @@ public class ChatServiceImpl implements ChatService {
@Override @Override
@Async @Async
public void sendMessageMysql(String username, String patientName, String idNum, String date, WebSocketSession session, String msg, List<WebSocketSession> webSocketSessionList) throws SQLException, IOException { 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()); CustomDataSource dataSource = datasourceMap.get(session.getId());
String databaseName = idNum;
ArrayList<Map> history = new ArrayList<>();
// 获取连接
if (dataSource == null) { if (dataSource == null) {
dataSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, databaseName); dataSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, idNum);
boolean status = dataSource.open(); boolean status = dataSource.open();
// 查询历史消息
if (status) { if (status) {
datasourceMap.put(session.getId(), dataSource); datasourceMap.put(session.getId(), dataSource);
// sessionDatabaseMap.put(session.getId(), databaseName);
// 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";
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()) {
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()));
// for (WebSocketSession webSocketSession : webSocketSessionList) {
// webSocketSession.sendMessage(new TextMessage(param.toJSONString().getBytes()));
// }
} 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 { }else {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("status", 1); jsonObject.put("status", 1);
jsonObject.put("msg", "数据库未创建, 请重新连接。"); jsonObject.put("msg", "数据库未创建, 请重新连接。");
jsonObject.put("msgType", "msg"); jsonObject.put("msgType", "msg");
try {
session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes())); session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes()));
session.close();
} catch (IOException e) {
e.printStackTrace();
}
return; return;
} }
} }
// 发消息, 入库 // 发消息, 入库
if (StringUtils.hasText(msg)) { if (StringUtils.hasText(msg)) {
String now = DateUtil.now(); String now = DateUtil.now();
JSONObject param = new JSONObject(); JSONObject param = new JSONObject();
param.put("msgType", "msg"); param.put("msgType", msgType);
param.put("createName", username);
param.put("createUser", username); param.put("createUser", username);
param.put("createTime", now); param.put("createTime", now);
param.put("content", msg); param.put("content", msg);
//System.out.println("param = " + param);
System.out.println("param = " + param); //System.out.println("webSocketSessionList = " + webSocketSessionList);
System.out.println("webSocketSessionList = " + webSocketSessionList);
// 广播消息 // 广播消息
for (WebSocketSession webSocketSession : webSocketSessionList) { for (WebSocketSession webSocketSession : webSocketSessionList) {
webSocketSession.sendMessage(new TextMessage(param.toJSONString().getBytes())); webSocketSession.sendMessage(new TextMessage(param.toJSONString().getBytes()));
} }
//
// 入库 // 入库
Connection connection = dataSource.getConnection(); Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = null; PreparedStatement preparedStatement = null;
try { try {
preparedStatement = connection.prepareStatement("INSERT INTO t_chat (content, create_time, create_user, create_name, deleted, revoked) VALUES (?, ?, ?, ?, ?, ?)"); preparedStatement = connection.prepareStatement("INSERT INTO t_chat (content, create_time, create_user, msg_type, deleted, revoked) VALUES (?, ?, ?, ?, ?, ?)");
preparedStatement.setString(1, msg); preparedStatement.setString(1, msg);
preparedStatement.setString(2, now); preparedStatement.setString(2, now);
preparedStatement.setString(3, username); preparedStatement.setString(3, username);
// String name = sysUser.getName(); // String name = sysUser.getName();
preparedStatement.setString(4, username); preparedStatement.setString(4, msgType);
preparedStatement.setInt(5, 0); preparedStatement.setInt(5, 0);
preparedStatement.setInt(6, 0); preparedStatement.setInt(6, 0);
preparedStatement.execute(); preparedStatement.execute();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
//// Map<String, WebSocketSession> sessionMap1 = databaseSessionMap.get(databaseName);
//// for (Map.Entry<String, WebSocketSession> entry : sessionMap1.entrySet()) {
//// WebSocketSession value = entry.getValue();
//// try {
//// value.sendMessage(new TextMessage(param.toJSONString().getBytes()));
//// } catch (IOException e) {
//// e.printStackTrace();
//// }
//// }
} }
} }

View File

@ -235,7 +235,7 @@ public class VitalSignServiceImpl implements VitalSignsService {
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
mySQLSource.close();
return R.ok(map); return R.ok(map);
} }

View File

@ -177,7 +177,6 @@ public class VitalSignTimerWS {
TimerTask timerTask = new TimerTask() { TimerTask timerTask = new TimerTask() {
@Override @Override
public void run() { public void run() {
Connection connection = finalDataSource.getConnection(); Connection connection = finalDataSource.getConnection();
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
// List<Map> vitalSignsList = vitalSignsService.getVitalSignsList(connection); // List<Map> vitalSignsList = vitalSignsService.getVitalSignsList(connection);