当前位置: 首页 > 图灵资讯 > 技术篇> 怎么在Spring Boot中集成WebSocket_@ServerEndpoint注解与全双工通信实战

怎么在Spring Boot中集成WebSocket_@ServerEndpoint注解与全双工通信实战

来源:图灵教育
时间:2026-03-22 21:43:16
@ServerendpointSpring 默认情况下,Boot不生效,也不能注入Spring Bean,手动注册Serverendpointexporter,仅限Tomcatat;更推荐使用Websockethandler+Websocketconfigurer实现原生支持。

@ServerEndpoint 注解在 Spring Boot 默认不生效,直接使用 404 或抛 java.lang.IllegalStateException: No suitable default RequestUpgradeStrategy —— 因为 Spring Boot 的嵌入式 Tomcat(或 Jetty/Undertow)没自动注册 WebSocket 手动配置容器支持。

为什么 @ServerEndpoint 不能直接在 Spring Boot 主类或 Bean 上用

Spring Boot 默认把 @ServerEndpoint 当作原生 Java EE 组件处理,不要去 Spring 容器生命周期。它不会被使用。 Spring 管理,不能注入 @Autowired 的 service、repository,也不能用 @Value 或 AOP。常见的现象是连接可以建造,但是 @OnOpen 里 this.userService 为 null,或者日志里没有办法进入。

实操建议:

  • 不要把 @ServerEndpoint 类声明为 @Component 或放在 @SpringBootApplication 指望扫描路径下的自动识别
  • 不要在 @ServerEndpoint 类里直接 @Autowired —— 除非你是显式桥接 Spring 上下文(见下一条)
  • 如果坚持用 @ServerEndpoint,必须通过 ServerEndpointExporter 暴露给容器,仅适用于 Tomcat
用 ServerEndpointExporter + @ServerEndpoint 最小可行配置

这是兼容性最好、变化最小的方案,适用于现有方案 @ServerEndpoint 代码想要快速运行的场景。注:只支持嵌入式 Tomcat,Jetty 和 Undertow 需换方案。

实操建议:

  • 在配置类中加一个 @Bean:
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
  • 确保 pom.xml 里有 spring-boot-starter-websocket,不是只靠 spring-boot-starter-web
  • @ServerEndpoint 类还是不能直接 @Autowired,但可通过 WebApplicationContextUtils.getWebApplicationContext(ctx.getServletContext()) 手动取 bean(不推荐,耦合重)
  • 路径写法必须带前缀,如 @ServerEndpoint("/ws/chat"),前端连 ws://localhost:8080/ws/chat,别漏 /ws
更推荐:用 Spring 的 WebSocketHandler + WebSocketConfigurer 替代 @ServerEndpoint

这才是 Spring Boot 原创游戏,自然支持依赖注射,拦截器,STOMP 协议扩展与所有嵌入式容器兼容。全双工通信的关键不在于注释,而在于 WebSocketSession 复用和线程安全操作。

导航零沫AI工具

零沫AI工具导航-AI导航新标杆,探索全球实用AI工具

下载

实操建议:

  • 实现 TextWebSocketHandler,重写 handleTextMessage 和 afterConnectionEstablished
  • 用 ConcurrentHashMap<string websocketsession></string> 存活连接,key 建议用业务 ID(如用户 ID),别用 session.getId() —— 它是随机 UUID,前端和后端难以对齐
  • 发消息时一定要检查 session.isOpen(),否则会抛 IllegalStateException: The session has been closed
  • 小心异步推送:不能在非 WebSocket 线程(如定时任务,HTTP 直接调整请求线程) session.sendMessage(),需用 session.sendMessage() 判断返回值是否成功,或重用 session.sendMessage(new TextMessage(...)) 并捕获 IOException
生产部署的跨域、握手失败和隐形坑

本地可通,上线断开?反向代理的概率很大(Nginx)或者负载平衡没有传输 WebSocket 升级头。错误现象包括:HTTP 200 但没升级成 ws,控制台报 Error during WebSocket handshake: Unexpected response code: 200。

实操建议:

  • Nginx 配置必须包括:
    location /ws/ {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
  • Spring Boot 默认情况在配置中关闭 CORS(spring.web.cors.enabled=false),改用 WebSocketConfigurer#registerStompEndpoints 或自定义 HandshakeInterceptor 控制 Origin
  • 别在 @OnMessage 或 handleTextMessage 在里面做耗时操作(如检查) DB、调整远程接口)会阻塞整个接口 WebSocket 线程池;应扔进去 TaskExecutor 异步处理
  • Tomcat 的 WebSocket 默认最大帧大小为 8KB,超长消息会悄然断开,需要 application.properties 改:server.tomcat.max-http-post-size=-1 和 spring.websocket.server.max-text-message-size=512000

真正困难的不是“如何连接”,而是连接生存期间的状态同步、异常重连策略和多实例 session 广播,以及当 WebSocketSession 如何让其他节点在某个节点失效后感知和清理? —— 一个注释解决不了这些问题。