自定义SecuritySessionKeyGenerator类,为每个客户端连接建立唯一的key
java
package com.pig4cloud.plugin.websocket.custom;
import com.pig4cloud.plugin.websocket.holder.SessionKeyGenerator;
import org.springframework.web.socket.WebSocketSession;
import java.util.UUID;
public class SecuritySessionKeyGenerator implements SessionKeyGenerator {
@Override
public Object sessionKey(WebSocketSession webSocketSession) {
Object user = webSocketSession.getAttributes().get("USER_KEY_ATTR_NAME");
// 添加随机后缀使每个连接键唯一
return user != null ? user + "-" + UUID.randomUUID().toString() : null;
}
}
重写WebSocketSessionHolder类方法
java
package com.pig4cloud.plugin.websocket.holder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import org.springframework.web.socket.WebSocketSession;
public final class WebSocketSessionHolder {
// 仅修改这一行:将Value改为Set类型
private static final Map<String, Set<WebSocketSession>> USER_SESSION_MAP = new ConcurrentHashMap<>();
private WebSocketSessionHolder() {
}
public static void addSession(Object sessionKey, WebSocketSession session) {
// 修改为支持多会话的添加方式
USER_SESSION_MAP.computeIfAbsent(sessionKey.toString(),
k -> new CopyOnWriteArraySet<>()).add(session);
}
public static void removeSession(Object sessionKey) {
// 移除时不再自动清除所有会话
Set<WebSocketSession> sessions = USER_SESSION_MAP.get(sessionKey.toString());
if (sessions != null) {
sessions.removeIf(s -> !s.isOpen()); // 只移除已关闭的连接
if (sessions.isEmpty()) {
USER_SESSION_MAP.remove(sessionKey.toString());
}
}
}
// 保持原有方法签名不变(兼容现有调用)
public static WebSocketSession getSession(Object sessionKey) {
Set<WebSocketSession> sessions = USER_SESSION_MAP.get(sessionKey.toString());
return sessions != null ? sessions.stream().findFirst().orElse(null) : null;
}
// 新增方法:获取用户的所有会话
public static Set<WebSocketSession> getSessions(Object sessionKey) {
return USER_SESSION_MAP.getOrDefault(sessionKey.toString(), Collections.emptySet());
}
// 保持原有方法不变
public static Collection<WebSocketSession> getSessions() {
List<WebSocketSession> allSessions = new ArrayList<>();
USER_SESSION_MAP.values().forEach(allSessions::addAll);
return allSessions;
}
// 保持原有方法不变
public static Set<String> getSessionKeys() {
return USER_SESSION_MAP.keySet();
}
}