spring cloud gateway 转发 ws 流量

由于项目中,存在ws服务,所以统一经过网关转发流量。
实际的链路:
在这里插入图片描述

  1. 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;
    }
  1. spring cloud gateway 的转发设置
    gateway:
      routes:
        - id: ws
          uri: ws://localhost:4443
          predicates:
            - Path=/**
            # 只匹配ws头
            - Header=Upgrade, websocket
          filters:
          	# 确保原始请求头中的 Host 不被网关自动替换成目标服务地址
            - PreserveHostHeader=true

根据特定的ws请求头来转发,避免根路径匹配,影响其他正常http请求

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值