在Spring Boot中使用WebSocket實現實時在線人數統計
在Spring Boot中使用WebSocket實現實時在線人數統計
在Spring Boot中使用WebSocket實現實時在線人數統計可以通過以下步驟完成。首先,需要添加相關的依賴和配置,然后創建WebSocket處理程序和相應的服務類。
添加依賴
在pom.xml文件中添加WebSocket和Spring Boot的相關依賴:
<dependencies>
<!-- Spring Boot Starter Web包含了Spring MVC和其他相關依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter WebSocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
配置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<String> 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