add: 一期代码

This commit is contained in:
republicline 2024-11-13 13:59:19 +08:00
parent 9591f28421
commit b17b11cf1a
2 changed files with 165 additions and 15 deletions

View File

@ -4,6 +4,7 @@ import com.rax.common.security.annotation.EnableRaxResourceServer;
import com.rax.common.swagger.annotation.EnableRaxDoc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
@ -15,12 +16,12 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@EnableRaxResourceServer
@EnableScheduling // 开启定时任务 -> 清除日志相关内容
// 一期下面解注, 二期注释掉
//@SpringBootApplication(exclude = MongoAutoConfiguration.class)
@SpringBootApplication
@SpringBootApplication(exclude = MongoAutoConfiguration.class)
//@SpringBootApplication
@ComponentScan(
basePackages = {"com.rax"},
excludeFilters = {
@ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.rax.vital.v1.*")
@ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.rax.vital.v2.*")
})
public class RaxAdminApplication extends SpringBootServletInitializer {

View File

@ -1,22 +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
@ -25,6 +32,23 @@ 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
@ -47,9 +71,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"))) {
@ -71,6 +95,8 @@ public class ChatHandler implements WebSocketHandler {
}
List<WebSocketSession> webSocketSessions = dbNameSessionList.get(dbName);
webSocketSessions.add(session);
// 创建数据库表
initTChatTable(dbName, session);
// ArrayList<String> sessionIDList = new ArrayList<>();
// for (WebSocketSession webSocketSession : webSocketSessions) {
// if (webSocketSession.isOpen()) {
@ -84,14 +110,31 @@ 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 {
String patientName = jsonObject.getString("patientName");
} 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 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);
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 {
String msgContent = "token无效,认证失败";
@ -112,7 +155,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);
}
@ -132,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) {
@ -157,4 +200,110 @@ 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` 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();
}
}
}