Nginx转发WebSocket到Spring Cloud Gateway并路由到Spring Boot服务

一、nginx location中配置

proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

二、Spring Cloud Gateway配置文件配置

spring:
  cloud:
    gateway:
      prefix: /open/v1
      routes:
        - id: platform-system          #http请求
          uri: lb://platform-system
          predicates:
            - Path=/platform/**
        - id: platform-system-websocket  #ws请求
          uri: lb:ws://platform-system
          predicates:
            - Path=/platform-socket/**

三、服务配置

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
@Slf4j
@Component
@ServerEndpoint(value = "/socket/wx/qrLogin")
public class WxQrLoginWebSocket {

    @OnOpen
    public void onOpen(Session session) {
        log.info("客户端连接成功:{}", session.getId());
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        try {
            sockets.remove(session.getId());
            log.info("【websocket消息】连接断开,sessionId:" + session.getId());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【websocket消息】收到客户端消息:" + message);
    }

    /**
     * 发送错误时的处理
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        try {
            //打印错误
            log.error("用户错误,原因:" + error.getMessage());
            error.printStackTrace();
            //关闭链接
            session.close();
            sockets.remove(session.getId());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

四、访问连接

(此处我的服务有ContextPath所以会加上platform-system)
nginx 443端口:wss://ip:port/open/v1/platform-socket/platform-system/socket/wx/qrLogin
nginx 80端口:ws://ip:port/open/v1/platform-socket/platform-system/socket/wx/qrLogin

你可能感兴趣的:(Nginx转发WebSocket到Spring Cloud Gateway并路由到Spring Boot服务)