在Spring Boot中使用WebSocket实现实时在线人数统计

开发 前端
这样,当有用户连接到WebSocket并发送消息时,greeting​方法将被调用,处理逻辑并将更新后的在线用户数发送到/topic/onlineUsers。

在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

责任编辑:武晓燕 来源: 路条编程
相关推荐

2023-11-17 09:35:58

2013-04-12 10:05:49

HTML5WebSocket

2022-02-08 17:07:54

Spring BooSpring Aop日志记录

2023-07-17 18:42:47

gRPCDemo项目

2024-04-09 09:05:47

SpringRedis系统

2024-04-02 08:17:40

2020-05-28 07:15:00

机器学习TensorFlow人工智能

2012-12-25 09:36:11

Storm大数据分析

2023-03-30 07:48:46

接口鉴权SpringBoot

2018-05-11 15:36:43

数据科学算法数据分析

2009-06-15 16:23:39

Eclipse中使用SEclipse RCP

2023-07-27 08:53:44

2022-07-26 16:54:08

QuartzJava

2017-12-27 15:16:35

Spring BootFlyway数据库

2022-02-09 20:39:52

Actuator应用监控

2022-05-30 10:14:10

jupyter

2023-09-01 08:46:44

2024-04-03 15:40:14

WebSocketWeb应用Spring

2018-06-27 14:50:06

Cloud StudiSpring Boot应用

2023-10-11 14:37:21

工具开发
点赞
收藏

51CTO技术栈公众号