在Spring Boot中使用WebSocket实现实时在线人数统计
在Spring Boot中使用WebSocket实现实时在线人数统计
在Spring Boot中使用WebSocket实现实时在线人数统计可以通过以下步骤完成。首先,需要添加相关的依赖和配置,然后创建WebSocket处理程序和相应的服务类。
添加依赖
在pom.xml文件中添加WebSocket和Spring Boot的相关依赖:
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-websocket
配置WebSocket
在application.properties文件中添加WebSocket的配置:
# WebSocket端口号 server.port=8080 # WebSocket端点 spring.websocket.endpoint=/ws
创建WebSocket处理程序
创建一个类来处理WebSocket连接和消息:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; @Controller public class WebSocketController { private final SimpMessagingTemplate messagingTemplate; private final OnlineUsersService onlineUsersService; @Autowired public WebSocketController(SimpMessagingTemplate messagingTemplate, OnlineUsersService onlineUsersService) { this.messagingTemplate = messagingTemplate; this.onlineUsersService = onlineUsersService; } @MessageMapping("/hello") public void greeting(WebSocketRequest request) { // 处理收到的消息,这里可以更新在线用户数等业务逻辑 // 在用户连接时调用此方法 onlineUsersService.userConnected(request.getName()); int onlineUsers = onlineUsersService.getOnlineUsersCount(); WebSocketResponse response = new WebSocketResponse("当前在线人数:" + onlineUsers); // 向客户端发送更新后的在线用户数 messagingTemplate.convertAndSendToUser(request.getName(), "/topic/onlineUsers", response); } }
创建WebSocket消息类
创建用于WebSocket通信的消息类:
public class WebSocketRequest { private String name; // Getter and Setter } javaCopy code public class WebSocketResponse { private String content; public WebSocketResponse(String content) { this.content = content; } // Getter }
配置WebSocket消息代理
在@SpringBootApplication注解的主应用程序类中添加配置,以启用WebSocket消息代理:
import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { // 启用简单的消息代理,以将消息发送到指定的前缀 config.enableSimpleBroker("/topic"); // 设置应用程序的消息目标前缀 config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { // 注册一个WebSocket端点,供客户端连接 registry.addEndpoint("/ws").withSockJS(); } }
创建服务类
创建一个服务类用于处理在线用户的统计逻辑:
import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.Set; @Service public class OnlineUsersService { // 使用Set存储在线用户的唯一标识,例如用户ID private final Set onlineUserIds = new HashSet(); // 用户连接时调用,将用户ID添加到在线用户集合中 public void userConnected(String userId) { onlineUserIds.add(userId); } // 用户断开连接时调用,将用户ID从在线用户集合中移除 public void userDisconnected(String userId) { onlineUserIds.remove(userId); } // 获取在线用户数 public int getOnlineUsersCount() { return onlineUserIds.size(); } }
更新WebSocket处理程序
更新WebSocketController类,使用服务类获取在线用户数:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; @Controller public class WebSocketController { private final SimpMessagingTemplate messagingTemplate; private final OnlineUsersService onlineUsersService; @Autowired public WebSocketController(SimpMessagingTemplate messagingTemplate, OnlineUsersService onlineUsersService) { this.messagingTemplate = messagingTemplate; this.onlineUsersService = onlineUsersService; } @MessageMapping("/hello") public void greeting(WebSocketRequest request) { // 处理收到的消息,这里可以更新在线用户数等业务逻辑 int onlineUsers = onlineUsersService.getOnlineUsersCount(); messagingTemplate.convertAndSend("/topic/onlineUsers", "当前在线人数:" + onlineUsers); } }
这样,当有用户连接到WebSocket并发送消息时,greeting方法将被调用,处理逻辑并将更新后的在线用户数发送到/topic/onlineUsers。
示例中完整代码,可以从下面网址获取:
https://gitee.com/jlearning/wechatdemo.git
https://github.com/icoderoad/wxdemo.git