Daily Code SpringBoot集成WebSocket

232 阅读1分钟

POM文件

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

配置文件Config

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

SocketService

// @param type 业务类型
// @param token 用户信息
@Component
@ServerEndpoint("/websocket/{type}/{token}")
public class SokcetService {

    private static SocketService socketService;
    //当前连接数
    private static int onlineCount = 0;
    //存放每个客户端对应的websocket对象
    private static ConcurrentHashMap<String, SocketService> socketMap = new ConcurrentHashMap<>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    private String uuid = "";
    
    // 注入的业务接口
    @Autowired
    private TestService testService;
    @Autowired
    private TokenService tokenService;
    
    // 初始化挂载bean
    @PostConstruct
    private void init() {
        socketService = this;
        socketService.testService = this.testService;
        socketService.tokenService = this.tokenService;
    }
    
    @OnOpen
    public void onOpen(Session session, @PathParam("type") String type, @PathParam("token") String token) {
        this.session = session;
        // 构造uuid -业务代码-需替换
        Long userId = socketService.tokenService.getUserId(token)
        
        this.uuid = String.format("%s%s%s", type, userId, IdUtil.randomUUID());
        if (!socketMap.containsKey(this.uuid)) {
            addOnlineCount();
        }
        socketMap.put(this.uuid, this);
    }
    
    // 服务端接收
    @OnMessage
    public void onMessage(@NotNull String message, Session session) {
        // 业务逻辑
    }
    
    // 服务器主动推送
    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    
    @OnClose
    public void onClose() {
        if (socketMap.containsKey(uuid)) {
            socketMap.remove(uuid);
            subOnlineCount();
        }
        log.debug("WebSocket---连接关闭, 用户id:{} 当前在线人数为:{}", uuid, getOnlineCount());
    }
    
    @OnError
    public void onError(Throwable error) {
        
    }
    
    // 获取在线人数
    private static synchronized int getOnlineCount() {
        return onlineCount;
    }

    // 在线人数加一
    private static synchronized void addOnlineCount() {
        socketService.onlineCount++;
    }

    // 在线人数减一
    private static synchronized void subOnlineCount() {
        socketService.onlineCount--;
    }
    
}