Spring Cloud Zuul 1.x的websocket支持实践

一、组件

Spring Cloud Netflix Edgware.SR3
spring-cloud-starter-zuul 1.3.5.RELEASE
nginx 1.14.0
Vue + SockJS + STOMP

二、实现

• 下游服务添加websocket支持,包括依赖、配置和使用
• zuul添加spring-cloud-netflix-zuul-websocket依赖
• zuul配置文件添加如下配置:下游使用websocket的服务和对应的websocket设置
zuul:
  ws:
    brokerages:
      下游使用websocket的服务名:
        end-points: /endpoint
        brokers: /brokers
        destination-prefixes:
• zuul添加websocket配置类
@Configuration
public class WebsokcetConfig {
    @Bean
    public ZuulPropertiesResolver zuulPropertiesResolver() {
        return wsBrokerage -> discoveryClient.getInstances(wsBrokerage.getId()).stream().findAny()
                .orElseGet(() -> new DefaultServiceInstance("", "", 0, false))
                .getUri().toString();
    }

    @Bean
    public WebSocketHttpHeadersCallback webSocketHttpHeadersCallback() {
        return userAgentSession -> new WebSocketHttpHeaders() {{
            add("Authorization",
                    new CustomBasicAuthRequestInterceptor(username, password).encodeBase64());
        }};
    }
}
• 前端使用sockJs和stomp连接网关的websocket
function connect() {
    var socket =
        new SockJS('http://zuul的地址/endpoint', null, {
        'transports': ['websocket']
    });
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        // 订阅用户消息通知
        stompClient.subscribe("/brokers",handleNotification);
    });
    function handleNotification(message) {
        showGreeting(message);
    }
}
• nginx添加对websocket的支持
location /gateway {
             //添加如下配置
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection "upgrade";
             proxy_set_header Host $host:$server_port;
        }

相关推荐