yangys
2024-05-19 9e5da8899bc21bb5b6b0a3c267108caa00199291
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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;
/**
 * 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 USER_SESSION_MAP.values().stream().flatMap(Collection::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;
    }
}