package com.qianwen.core.websocket.holder;
|
|
import java.util.Collection;
|
import java.util.HashSet;
|
import java.util.Map;
|
import java.util.Set;
|
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.stream.Collectors;
|
import org.springframework.web.socket.WebSocketSession;
|
|
public class WebSocketSessionHolder {
|
private static final Map<Object, Set<WebSocketSession>> USER_SESSION_MAP = new ConcurrentHashMap();
|
|
private WebSocketSessionHolder() {
|
}
|
|
public static void addSession(Object sessionKey, WebSocketSession session) {
|
USER_SESSION_MAP.put(sessionKey, combineSessionWithSameKey(sessionKey, session));
|
}
|
|
public static void removeSession(Object sessionKey) {
|
USER_SESSION_MAP.remove(sessionKey);
|
}
|
|
public static void removeSession(Object sessionKey, WebSocketSession session) {
|
Set<WebSocketSession> webSocketSessions = USER_SESSION_MAP.get(sessionKey);
|
webSocketSessions.remove(session);
|
}
|
|
public static Set<WebSocketSession> getSession(Object sessionKey) {
|
return USER_SESSION_MAP.get(sessionKey);
|
}
|
|
public static Collection<WebSocketSession> getSessions() {
|
return (Collection) USER_SESSION_MAP.values().stream().flatMap((v0) -> {
|
return v0.stream();
|
}).collect(Collectors.toList());
|
}
|
|
public static Set<Object> SessionKeys() {
|
return USER_SESSION_MAP.keySet();
|
}
|
|
private static Set<WebSocketSession> combineSessionWithSameKey(Object sessionKey, WebSocketSession session) {
|
Set<WebSocketSession> result = USER_SESSION_MAP.getOrDefault(sessionKey, new HashSet());
|
result.add(session);
|
return result;
|
}
|
}
|