70 lines
2.7 KiB
Java

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.supervision.controller;
import com.supervision.constant.UserTokenConstant;
import com.supervision.websocket.UserResourceCheck;
import com.supervision.websocket.WebSocketSessionPool;
import com.supervision.websocket.dto.WebSocketLoginDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
@Component
@Slf4j
@ServerEndpoint("/webSocket/{uuid}/{userId}")
public class WebSocketServer {
private static RedisTemplate<String, String> redisTemplate;
private static UserResourceCheck userResourceCheck;
// 因为是ServerEndpoint是多例,所以需要这样注入
@Autowired
public void setUserResourceCheck(UserResourceCheck userResourceCheck) {
WebSocketServer.userResourceCheck = userResourceCheck;
}
// 因为是ServerEndpoint是多例,所以需要这样注入
@Autowired
public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
WebSocketServer.redisTemplate = redisTemplate;
}
/**
* 有客户端连接成功
*/
@OnOpen
public void onOpen(Session session, @PathParam(value = "uuid") String uuid, @PathParam(value = "userId") String userId) {
// 校验资源数量,并保存
userResourceCheck.achieveDiagnoseResourceAndOpenConnection(uuid, userId, session);
WebSocketSessionPool.SESSION_POOL.put(uuid, session);
log.info("用户:{},UUID:{}登录成功", userId, uuid);
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session, @PathParam(value = "uuid") String uuid, @PathParam(value = "userId") String userId) {
redisTemplate.opsForHash().delete(UserTokenConstant.USER_WEBSOCKET_CACHE, uuid);
WebSocketSessionPool.SESSION_POOL.remove(uuid);
log.info("用户:{},uuid:{}关闭从Redis中移除,当前连接数为:{}", userId, uuid, redisTemplate.opsForHash().size(UserTokenConstant.USER_WEBSOCKET_CACHE));
}
/**
* 发生错误
*/
@OnError
public void onError(Session session, @PathParam(value = "uuid") String uuid, @PathParam(value = "userId") String userId, Throwable throwable) {
redisTemplate.opsForHash().delete(UserTokenConstant.USER_WEBSOCKET_CACHE, uuid);
WebSocketSessionPool.SESSION_POOL.remove(uuid);
log.error("用户:{},uuid:{}发生错误从Redis中移除,当前连接数为:{}", userId, uuid, redisTemplate.opsForHash().size(UserTokenConstant.USER_WEBSOCKET_CACHE), throwable);
}
}