• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

nginx 代理geteway网关转发的websocket

武飞扬头像
落杉丶
帮助2

前言

目前在实际项目(springboot)中需要用到通过网关来转发实际的请求。
而在网上找了很久,帖子比较分散,且不能一次性完成操作。
多次尝试之后终于结束,身为一个苦逼程序员,我很欣慰。
所以就此记录一下。

nginx配置

这里的前提就是你已经有网关以及自服务的环境,并且你的网关转发websocket请求已经成功.
当前,如果是想问普通的项目nginx代理的形式,这边我也标注一下

下面是完整的nginx配置。nginx的版本:nginx-1.22.0


worker_processes  1;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    
    sendfile        on;
    keepalive_timeout  65;
	
	# 代理websocket
	map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

	# nginx配置代理gateway与websocket服务
    server {
        listen       10777;
        server_name  localhost;
    # 这里代理的是gateway
        location / {
			proxy_pass http://192.168.0.2:10117;
				proxy_set_header X-real-ip &remote_addr;
				proxy_set_header Host $Host;
        }
    # 这里代理的是gateway转发的websocket服务
        location /socket/ws {
		   proxy_pass http://192.168.0.2:10117;
		    proxy_http_version 1.1;
			proxy_connect_timeout 4s;              
            proxy_read_timeout 3600s;   #默认60s没有传输数据就会关闭,延长时间            
            proxy_send_timeout 12s;    
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
		  
		}
    
    }


	# 一下是nginx直接代理spring boot的websocket连接。
	 server {
		  listen    11127;
		  server_name localhost;
		  
		  location /ws {
		   proxy_pass http://192.168.0.102:10127;
		    proxy_http_version 1.1;
			proxy_connect_timeout 4s;              
            proxy_read_timeout 3600s;   #默认60s没有传输数据就会关闭,延长时间            
            proxy_send_timeout 12s;    
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
		}
	}
	
}

学新通

如果你是老手或者足够幸运,配置文件换上之后,你就完成了配置。

springboot项目的websocket

为了确保大家的环境一致性,这里贴出实际项目中的配置,当前这可能不能完全包括实际生产需求,但以demo形式可以运行之后,在给予优化应该也是一建方便的事情。
学新通

springboot项目的geteway

一下是gateway的配置websocket代理
uri: lb:ws://springboot-config
是最为关键的一行。


        # 转发websocket
        - id: springboot-config
          filters:
            - StripPrefix=1  # 转发之前去掉第1层路径(此次访问下级路由时由原/get/value变成了/nacos/get/value)
          uri: lb:ws://springboot-config
          predicates:
            - name: Path
              args[pattern]: /socket/**  # 断言,路径相匹配的进行路由
              

测试是否连接成功

这里用到的是ApiPost软件,可以直接连接到项目的ws连接。
学新通

配置nginx的遇到的问题

在于直接使用大佬的配置时,可能使nginx不能启动以及关闭,又因为nginx的特性,导致我在实际中没有及时的发现我修改的配置导致nginx无法启动了,以至于浪费了时间。大家在集成的时候一定要注意。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbfgia
系列文章
更多 icon
同类精品
更多 icon
继续加载