76 lines
2.2 KiB
Java
76 lines
2.2 KiB
Java
package com.gxwebsoft.common.core.socketio.cache;
|
|
|
|
import com.corundumstudio.socketio.SocketIOClient;
|
|
import com.corundumstudio.socketio.SocketIOServer;
|
|
import org.springframework.stereotype.Component;
|
|
import org.springframework.util.CollectionUtils;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.UUID;
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
|
|
/**
|
|
* @Author
|
|
* @Description 用户信息缓存
|
|
* @Date 14:00 2022/1/21
|
|
* @Param
|
|
* @return
|
|
**/
|
|
@Component
|
|
public class ClientCache {
|
|
|
|
private static Map<String, HashMap<UUID, SocketIOClient>> concurrentHashMap = new ConcurrentHashMap<>();
|
|
|
|
private static SocketIOServer socketIOServer;
|
|
|
|
public static SocketIOServer getSocketIOServer() {
|
|
return socketIOServer;
|
|
}
|
|
|
|
public static void setSocketIOServer(SocketIOServer instance) {
|
|
socketIOServer = instance;
|
|
}
|
|
public void saveClient(String userId,UUID sessionId,SocketIOClient socketIOClient){
|
|
HashMap<UUID, SocketIOClient> sessionIdClientCache = concurrentHashMap.get(userId);
|
|
if(sessionIdClientCache == null){
|
|
sessionIdClientCache = new HashMap<>();
|
|
}
|
|
sessionIdClientCache.put(sessionId,socketIOClient);
|
|
concurrentHashMap.put(userId,sessionIdClientCache);
|
|
}
|
|
|
|
|
|
public HashMap<UUID,SocketIOClient> getUserClient(String userId){
|
|
return concurrentHashMap.get(userId);
|
|
}
|
|
|
|
public void deleteSessionClientByUserId(String userId,UUID sessionId){
|
|
concurrentHashMap.get(userId).remove(sessionId);
|
|
}
|
|
|
|
|
|
public void deleteUserCacheByUserId(String userId){
|
|
concurrentHashMap.remove(userId);
|
|
}
|
|
|
|
public int getOnLineCount(){
|
|
return concurrentHashMap.size();
|
|
}
|
|
|
|
public void sendUserEvent(String userId,String event, Object message) {
|
|
// 发送到接收方
|
|
HashMap<UUID, SocketIOClient> userClient = concurrentHashMap.get(userId);
|
|
|
|
// 查看对方是否在线
|
|
if(!CollectionUtils.isEmpty(userClient)){
|
|
for (UUID uuid : userClient.keySet()) {
|
|
SocketIOClient ioClient = userClient.get(uuid);
|
|
ioClient.sendEvent(event, message);
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|