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

Spring Cloud Gateway下微服务WebSocket连接失败排查求助

问题分析与修复方案

核心问题

你的WebSocket连接失败(404)主要源于三个配置错误:

  1. 网关路由路径不匹配:前端请求的/websocket路径,在网关配置中没有对应路由规则,导致网关无法转发请求到message-service。
  2. WebSocket负载均衡URI格式错误:直接使用ws://message-service无法通过Eureka实现服务发现,必须采用负载均衡专用的WebSocket URI格式。
  3. 缺少WebSocket头信息处理:Spring Cloud Gateway默认会修改HTTP头,需配置过滤器保留WebSocket握手必需的Upgrade和Connection头。

具体修复步骤

1. 修正Spring Cloud Gateway配置(application.yml)

更新message-service的路由规则,调整URI格式并添加必要的过滤器:

server:
  port: 9000
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
          - Path=/user/**
        - id: room-service
          uri: lb://room-service
          predicates:
            - Path=/room/**
        - id: message-service-websocket
          uri: lb:ws://message-service  # 使用负载均衡的WebSocket URI格式
          predicates:
            - Path=/websocket/**  # 匹配WebSocket端点路径
          filters:
            - DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_FIRST
            - AddResponseHeader=Access-Control-Allow-Origin, *
            # 保留WebSocket握手必需的头信息
            - DedupeResponseHeader=Upgrade Connection, RETAIN_FIRST

  application:
    name: gateway-service
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka

2. 确认message-service的WebSocket端点配置

你的message-service已正确注册/websocket端点,无需修改,但要确保服务已成功注册到Eureka(可访问http://localhost:8761查看实例状态)。

3. 调整room-service前端连接代码

保持原连接地址即可,因为网关路由已匹配/websocket/**:

<script>
    var socket = new SockJS('http://localhost:9000/websocket');
    var stompClient = Stomp.over(socket);

    stompClient.connect({}, function (frame) {
        var roomId = 1001;
        console.log("connected: " + frame );
        stompClient.subscribe('/topic/messages', function (message) {
            console.log(message);
        });
    });
</script>

验证步骤

  1. 重启网关服务和message-service,确认Eureka中两个服务均处于UP状态。
  2. 用Postman测试WebSocket连接:使用ws://localhost:9000/websocket,正常情况下会返回101 Switching Protocols状态码。
  3. 启动room-service,查看浏览器控制台是否能正常建立连接并接收消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:32:02