开发指南148-WebSocket-后端

首先上组件

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>

然后实现:

复制代码
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer

最关键的是

复制代码
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws")
            .setAllowedOrigins(allowedOrigins.split(","))
            // 握手阶段把 URL 上的 token 存进 session attributes(鉴权兜底通道)
            .addInterceptors(tokenHandshakeInterceptor())
            .withSockJS()
            .setSessionCookieNeeded(false)
            // SockJS 层心跳 25s:SockJS 在 http 轮询降级时靠它保活
            .setHeartbeatTime(25_000)
            .setTaskScheduler(heartbeatScheduler())
            .setDisconnectDelay(30_000);
}

其中必须写明具体Origins,写* 一定前端跨域失败(前端底层自身问题)

实现

复制代码
public class WebSocketAuthInterceptor implements ChannelInterceptor 进行token校验

实现后台发送类:

复制代码
public class LocalStompPublisher 

其中:

复制代码
public String send(PushEnvelope envelope) {
    try {
        String destination = envelope.getDestination();

        // 投递前先看有没有订阅者
        int subscribers = subscriptionTracker.count(destination);
        if (subscribers == 0) {
            CommonsUtil.debugLog("destination=" + destination + " 当前无订阅者");
        } else {
            messagingTemplate.convertAndSend(destination, envelope.getPayloadJson());
            CommonsUtil.debugLog("本地投递成功 destination=" + destination);
        }
        return "";
    } catch (Exception e) {
        CommonsUtil.recordLog(e);
        return "ERROR:" + e.getMessage();
    }
}
相关推荐
yyuuuzz6 小时前
跨境站点日志时区混乱的排查记录
运维·服务器·网络·云计算·aws·1024程序员节
GlobalInfo6 小时前
全球及中国风电叶片检测机器人行业研究报告(2026版):市场现状、行业前景与占有率分析
运维·网络·人工智能·机器人
运维行者_8 小时前
网络监控工具怎么选?从设备监控到智能运维的能力清单
运维·服务器·开发语言·网络·人工智能·支持向量机·php
2401_868534788 小时前
陈冲2026年上海纽约大学全英文毕业演讲
服务器·网络
FPGA小迷弟10 小时前
FPGA开发Vivado Block Design/Vitis/SDK/xlinx/开发教程,保姆级别,一看就会!
网络协议·tcp/ip·fpga开发·verilog·fpga
FPGA小迷弟10 小时前
基于FPGA实现智能网卡的概念,什么是智能网卡
网络协议·tcp/ip·fpga开发·verilog·fpga
DYWorker00112 小时前
第1课:基于正点原子RK3568开发板读懂Linux内核
linux·运维·网络
Lzg_na14 小时前
数据链路层差错控制使用的算法详解
网络
努力努力再努力wz14 小时前
【C++ 高阶系列】C++ 高性能网络编程:当 Reactor 遇见协程:从 epoll 回调到异步 MySQL,彻底打通任务挂起与恢复
网络·c++·mysql
loulanyue_14 小时前
当AI学会自主攻击与渗透破壁:Agent行为链失控与Mythos级攻防颠覆下的安全范式重构——读CNCC2026第六届网络生态治理论坛实录
网络·人工智能·安全