You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot WebSocket无法统计订阅者数量问题求助

问题:Spring Boot WebSocket无法获取订阅用户数

我在学习Spring Boot官方WebSocket基础教程时,尝试修改代码实现控制台打印指定频道的订阅用户数,但折腾了数小时仍未解决。查阅多篇StackOverflow帖子后,按照其中一篇的建议注入SimpUserRegistry来获取用户,在控制器中添加了如下代码:

@Controller
public class GreetingController {
    @Autowired
    private SimpUserRegistry userRegistry;

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        Set<SimpUser> subscribedUsers = userRegistry.getUsers();
        System.out.println("User amount: " + subscribedUsers.size()); // 始终输出:0
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }
}

但上述代码的打印语句始终输出0。我有Socket.IO开发背景,原本以为Spring Boot会有类似便捷的统计方式,也看过有人手动实现订阅服务类,但都没能解决问题。

补充说明:有一篇帖子指出了问题的核心——WebSocket事件中的Principal始终为null,这会导致SimpUserRegistry无法正确追踪用户,进而无法获取到订阅用户数。

内容的提问来源于stack exchange,提问作者NoobSailboat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 06:25:24