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

27次阅读

共计 1353 个字符,预计需要花费 4 分钟才能阅读完成。

一、组件

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;
        }

正文完
 0