feat: 优化webSocket的连接问题

This commit is contained in:
2025-12-24 19:01:24 +08:00
parent 68e2084f57
commit b731476302
8 changed files with 298 additions and 41 deletions
@@ -33,7 +33,7 @@ import java.util.concurrent.atomic.AtomicInteger;
* 使用主题订阅模式,所有设备共享一个WebSocket连接
* 基于Spring WebSocket实现
*
* @author lishilin
* @author dzc
* @date 2025-01-19
*/
@Slf4j
@@ -72,6 +72,11 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
*/
private volatile WebSocketSession session;
/**
* 发送消息锁(WebSocket不是线程安全的,需要同步发送)
*/
private final Object sendLock = new Object();
/**
* 重连次数
*/
@@ -668,14 +673,19 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
}
/**
* 发送消息
* 发送消息(线程安全)
* WebSocket session 不是线程安全的,必须同步发送以避免 TEXT_PARTIAL_WRITING 错误
*/
public void send(String message) {
if (session != null && session.isOpen()) {
try {
session.sendMessage(new TextMessage(message));
} catch (Exception e) {
log.error("发送消息失败: {}", e.getMessage(), e);
synchronized (sendLock) {
try {
if (session != null && session.isOpen()) {
session.sendMessage(new TextMessage(message));
}
} catch (Exception e) {
log.error("发送消息失败: {}", e.getMessage(), e);
}
}
} else {
log.warn("WebSocket未连接,无法发送消息");
@@ -265,6 +265,30 @@ public class SubscriptionPoolService {
}
}
/**
* 清理所有订阅(服务重启时调用)
* 删除所有以 device:sub: 开头的 Redis key
*
* @return 清理的 key 数量
*/
public int clearAllSubscriptions() {
int deletedCount = 0;
try {
// 查找所有订阅相关的 key
Set<String> keys = redisTemplate.keys(KEY_PREFIX + "*");
if (keys != null && !keys.isEmpty()) {
deletedCount = keys.size();
redisTemplate.delete(keys);
log.info("清理所有订阅: 删除了 {} 个 Redis key", deletedCount);
} else {
log.info("清理所有订阅: 没有找到订阅记录");
}
} catch (Exception e) {
log.error("清理所有订阅失败: {}", e.getMessage(), e);
}
return deletedCount;
}
/**
* 打印当前订阅状态(调试用)
*/