diff --git a/upms/upms-biz/src/main/java/com/rax/admin/timmer/MySqlTimer.java b/upms/upms-biz/src/main/java/com/rax/admin/timmer/MySqlTimer.java index 88395ef..907d110 100644 --- a/upms/upms-biz/src/main/java/com/rax/admin/timmer/MySqlTimer.java +++ b/upms/upms-biz/src/main/java/com/rax/admin/timmer/MySqlTimer.java @@ -16,17 +16,16 @@ import java.util.concurrent.TimeUnit; * @author: republicline * @description: mysql定时备份 */ -@Slf4j @Component +@Slf4j public class MySqlTimer { public static void main(String[] args) throws Exception { - MySqlTimer mySqlTimer = new MySqlTimer(); - mySqlTimer.backup(); + backup(); } - @Scheduled(cron = "0 0 15 * * 1") - public void backup() throws Exception { + @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"; @@ -35,7 +34,7 @@ public class MySqlTimer { Connection connection = DriverManager.getConnection(connectionUrl, username, password); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SHOW DATABASES"); - System.out.println("MySQL服务器上的数据库列表:"); +// System.out.println("MySQL服务器上的数据库列表:"); while (resultSet.next()) { String databaseName = resultSet.getString(1); @@ -57,7 +56,6 @@ public class MySqlTimer { connection.close(); } - /** * 备份mysql数据库 * @@ -69,7 +67,7 @@ public class MySqlTimer { * @param dbName 数据库名 * @throws Exception */ - public void dbBackUpMysql(String ip, String port, String username, String pwd, String path, String 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()); @@ -110,6 +108,7 @@ public class MySqlTimer { } else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) { process = Runtime.getRuntime().exec("/bin/sh -c" + sb); } else { + log.error("暂不支持该操作系统,进行数据库备份或还原!"); throw new Exception("暂不支持该操作系统,进行数据库备份或还原!"); } diff --git a/upms/upms-biz/src/main/java/com/rax/vital/controller/MachineController.java b/upms/upms-biz/src/main/java/com/rax/vital/controller/MachineController.java index 5be4f3d..3c0a5e4 100644 --- a/upms/upms-biz/src/main/java/com/rax/vital/controller/MachineController.java +++ b/upms/upms-biz/src/main/java/com/rax/vital/controller/MachineController.java @@ -1,130 +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 dynamicDataSources = new ConcurrentHashMap<>(); -// -// // 仪器端生命体征数据入库 -// @PostMapping("/save") -// @Inner(value = false) -// public R 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 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); -// } -// -// }); -// } -//} +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 dynamicDataSources = new ConcurrentHashMap<>(); + + // 仪器端生命体征数据入库 + @PostMapping("/save") + @Inner(value = false) + public R 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 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); + } + + }); + } +} diff --git a/upms/upms-biz/src/main/java/com/rax/vital/v1/handler/ChatHandler.java b/upms/upms-biz/src/main/java/com/rax/vital/v1/handler/ChatHandler.java index d8f611b..ef7bc68 100644 --- a/upms/upms-biz/src/main/java/com/rax/vital/v1/handler/ChatHandler.java +++ b/upms/upms-biz/src/main/java/com/rax/vital/v1/handler/ChatHandler.java @@ -1,29 +1,22 @@ 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.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; public class ChatHandler implements WebSocketHandler { @Resource @@ -32,23 +25,6 @@ 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 timerTaskMap = new ConcurrentHashMap(); // dbName -> sessionList @@ -71,9 +47,9 @@ public class ChatHandler implements WebSocketHandler { OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); if (authorization != null) { String username = authorization.getPrincipalName(); - String payload = (String) message.getPayload(); JSONObject jsonObject = JSONObject.parseObject(payload); + if ("heartbeat".equals(jsonObject.getString("msgType"))) { // session.sendMessage(new TextMessage("")); } else if ("init".equals(jsonObject.getString("msgType"))) { @@ -95,8 +71,6 @@ public class ChatHandler implements WebSocketHandler { } List webSocketSessions = dbNameSessionList.get(dbName); webSocketSessions.add(session); - // 创建数据库表 - initTChatTable(dbName, session); // ArrayList sessionIDList = new ArrayList<>(); // for (WebSocketSession webSocketSession : webSocketSessions) { // if (webSocketSession.isOpen()) { @@ -110,31 +84,14 @@ public class ChatHandler implements WebSocketHandler { // 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"); + } else { + String patientName = jsonObject.getString("patientName"); String dbName = 'a' + jsonObject.getString("idNum"); - //String date = jsonObject.getString("date"); - String msgType = jsonObject.getString("msgType"); + String date = jsonObject.getString("date"); // 消息内容 - String content = jsonObject.getString("msg"); + String msg = jsonObject.getString("msg"); List 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); + chatService.sendMessageMysql(username, patientName, dbName, date, session, msg, webSocketSessions); } } else { String msgContent = "token无效,认证失败"; @@ -155,7 +112,7 @@ public class ChatHandler implements WebSocketHandler { 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); } @@ -175,7 +132,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) { @@ -200,110 +157,4 @@ public class ChatHandler implements WebSocketHandler { 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(); - } - } - - } diff --git a/upms/upms-biz/src/main/java/com/rax/vital/v1/medicine/service/impl/ChatServiceImpl.java b/upms/upms-biz/src/main/java/com/rax/vital/v1/medicine/service/impl/ChatServiceImpl.java index 5a17ef5..718bc95 100644 --- a/upms/upms-biz/src/main/java/com/rax/vital/v1/medicine/service/impl/ChatServiceImpl.java +++ b/upms/upms-biz/src/main/java/com/rax/vital/v1/medicine/service/impl/ChatServiceImpl.java @@ -59,60 +59,135 @@ public class ChatServiceImpl implements ChatService { @Override @Async - public void sendMessageMysql(String username, String patientName, String idNum, String msgType, WebSocketSession session, String msg, List webSocketSessionList) throws SQLException, IOException { + public void sendMessageMysql(String username, String patientName, String idNum, String date, WebSocketSession session, String msg, List webSocketSessionList) throws SQLException, IOException { CustomDataSource dataSource = datasourceMap.get(session.getId()); + String databaseName = idNum; + ArrayList history = new ArrayList<>(); + // 获取连接 if (dataSource == null) { - dataSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, idNum); + dataSource = new MySQLSource(mysqlHost, mysqlPassword, mysqlUsername, databaseName); boolean status = dataSource.open(); + // 查询历史消息 if (status) { datasourceMap.put(session.getId(), dataSource); - }else { +// sessionDatabaseMap.put(session.getId(), databaseName); +// Map 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 { JSONObject jsonObject = new JSONObject(); jsonObject.put("status", 1); jsonObject.put("msg", "数据库未创建, 请重新连接。"); jsonObject.put("msgType", "msg"); - session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes())); + try { + session.sendMessage(new TextMessage(jsonObject.toJSONString().getBytes())); + session.close(); + } catch (IOException e) { + e.printStackTrace(); + } return; } } - // 发消息, 入库 if (StringUtils.hasText(msg)) { String now = DateUtil.now(); JSONObject param = new JSONObject(); - param.put("msgType", msgType); + param.put("msgType", "msg"); + param.put("createName", username); 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, msg_type, deleted, revoked) VALUES (?, ?, ?, ?, ?, ?)"); + preparedStatement = connection.prepareStatement("INSERT INTO t_chat (content, create_time, create_user, create_name, deleted, revoked) VALUES (?, ?, ?, ?, ?, ?)"); preparedStatement.setString(1, msg); preparedStatement.setString(2, now); preparedStatement.setString(3, username); // String name = sysUser.getName(); - preparedStatement.setString(4, msgType); + preparedStatement.setString(4, username); preparedStatement.setInt(5, 0); preparedStatement.setInt(6, 0); preparedStatement.execute(); } catch (SQLException e) { e.printStackTrace(); } +//// Map sessionMap1 = databaseSessionMap.get(databaseName); +//// for (Map.Entry entry : sessionMap1.entrySet()) { +//// WebSocketSession value = entry.getValue(); +//// try { +//// value.sendMessage(new TextMessage(param.toJSONString().getBytes())); +//// } catch (IOException e) { +//// e.printStackTrace(); +//// } +//// } } }