ws配置 zuul_Spring Cloud Zuul 1.x的websocket支持实践

本文介绍了如何在Spring Cloud Netflix Edgware.SR3中配置Zuul来支持WebSocket。首先,下游服务需要添加WebSocket支持,包括相关依赖、配置和使用。接着,Zuul通过引入`spring-cloud-netflix-zuul-websocket`依赖,并在配置文件中定义下游WebSocket服务的end-point和brokerages。然后,创建WebSocket配置类,提供ZuulPropertiesResolver和WebSocketHttpHeadersCallback。前端使用SockJS和STOMP通过Zuul网关连接到下游服务的WebSocket端点。最后,Nginx配置代理以支持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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值