spring cloud gateway 转发 ws 流量
由于项目中,存在ws服务,所以统一经过网关转发流量。
实际的链路:
- nginx的配置:
http 块的配置
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
这里使用map的原因:可以根据请求头的 $http_upgrade 值动态设置 Connection 头
- 如果 $http_upgrade 存在(非空),说明是 WebSocket 请求 → 设置 Connection: upgrade
- 如果为空(普通请求)→ 设置 Connection: close
这样就能安全地区分 WebSocket 和普通请求,避免不必要的问题。
server 块的配置
location / {
proxy_pass http://apibackend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 保留 WebSocket 所需头部
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
# 防止 WebSocket 被缓存或打断
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}
- spring cloud gateway 的转发设置
gateway:
routes:
- id: ws
uri: ws://localhost:4443
predicates:
- Path=/**
# 只匹配ws头
- Header=Upgrade, websocket
filters:
# 确保原始请求头中的 Host 不被网关自动替换成目标服务地址
- PreserveHostHeader=true
根据特定的ws请求头来转发,避免根路径匹配,影响其他正常http请求