|
|
@@ -5,6 +5,7 @@ import com.doc.chat.domain.ChatMsg;
|
|
|
import com.doc.chat.service.IChatMsgService;
|
|
|
import com.doc.chat.service.impl.ChatMsgServiceImpl;
|
|
|
import com.doc.common.constant.CacheConstants;
|
|
|
+import com.doc.common.core.redis.RedisCache;
|
|
|
import com.doc.common.utils.spring.SpringUtils;
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
@@ -19,6 +20,7 @@ import javax.websocket.Session;
|
|
|
import javax.websocket.server.PathParam;
|
|
|
import javax.websocket.server.ServerEndpoint;
|
|
|
import java.io.IOException;
|
|
|
+import java.util.ArrayList;
|
|
|
import java.util.List;
|
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
|
|
|
|
@@ -33,6 +35,8 @@ import java.util.concurrent.ConcurrentHashMap;
|
|
|
public class WebSocketServer {
|
|
|
private IChatMsgService msgService = SpringUtils.getBean(ChatMsgServiceImpl.class);
|
|
|
private RedisTemplate redisTemplate = SpringUtils.getBean(StringRedisTemplate.class);
|
|
|
+
|
|
|
+ private RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
|
|
|
/**
|
|
|
* 保存 组id->组成员 的映射关系
|
|
|
* 之所以使用ConcurrentHashMap因为这个是线程安全的
|
|
|
@@ -47,6 +51,7 @@ public class WebSocketServer {
|
|
|
//需要通知其他的客户端,将所有的用户的用户名发送给客户端
|
|
|
//将当前连接的session存储到redis中
|
|
|
currentMap.put(uid, session);
|
|
|
+ setOnlineUserListCache();
|
|
|
log.info("用户(ID:{})建立连接!", uid);
|
|
|
try {
|
|
|
session.getBasicRemote().sendText("连接成功");
|
|
|
@@ -94,7 +99,8 @@ public class WebSocketServer {
|
|
|
this.sendClusterMessage(message);
|
|
|
}
|
|
|
} catch (Exception e) {
|
|
|
- e.printStackTrace();
|
|
|
+ log.error("会话异常!" + e.getMessage());
|
|
|
+// e.printStackTrace();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -105,6 +111,18 @@ public class WebSocketServer {
|
|
|
public void onClose(@PathParam("uid") Long uid, Session session) {
|
|
|
log.info("用户(ID:{})关闭连接!", uid);
|
|
|
currentMap.remove(uid);
|
|
|
+ setOnlineUserListCache();
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 设置在线用户列表
|
|
|
+ */
|
|
|
+ private void setOnlineUserListCache() {
|
|
|
+ List<Long> onlineUsers = new ArrayList<>(currentMap.keySet());
|
|
|
+ redisCache.deleteObject(CacheConstants.ONLINE_USERS);
|
|
|
+ if (onlineUsers.size() > 0) {
|
|
|
+ redisCache.setCacheList(CacheConstants.ONLINE_USERS, onlineUsers);
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -126,8 +144,8 @@ public class WebSocketServer {
|
|
|
session.getBasicRemote().sendText(JSON.toJSONString(msg));
|
|
|
}
|
|
|
} catch (Exception e) {
|
|
|
- log.info("会话异常!" + e.getMessage());
|
|
|
- e.printStackTrace();
|
|
|
+ log.error("会话异常!" + e.getMessage());
|
|
|
+// e.printStackTrace();
|
|
|
}
|
|
|
}
|
|
|
}
|