yangys
2024-05-18 cc0bdfb33ef638dfafe3185c92c7076d815e1c9b
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;
 
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;
    }
}