欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

WebSocket 应用程序的 Nginx 代理和负载平衡

最编程 2024-04-18 20:46:41
...

WebSocket 介绍

WebSocket是目前比较成熟的技术了,大部分现在的浏览器都支持WebSocket,比如Firefox,IE,Chrome,Safari,Opera,并且越来越多的服务器框架现在也同样支持WebSocket。WebSocket 和HTTP虽然是不同协议,但是两者“握手”方式兼容。通过HTTP升级机制,使用HTTP的Upgrade和Connection协议头的方式可以将连接从HTTP升级为WebSocket。NGINX从1.3版本开始支持WebSocket,其可以作为一个反向代理和为WebSocket程序做负载均衡。即将Upgrade: websocket和Connection: Upgrade必须设置一致

GET /app/websocket/ HTTP/1.1
Host: localhost
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dddskkkdsjss
Origin: http://localhost
Sec-WebSocket-Version: 13

一个典型的Websocket握手请求如下:

客户端请求:

GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
Sec-WebSocket-Key: sN9cRrP/n9NdMgdcy2VJFQ==
Sec-WebSocket-Version: 13


服务器回应:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: fFBooB7FAkLlXgRSz0BT3v4hq5s=
Sec-WebSocket-Location: ws://example.com/

二.Nginx开启websocket代理功能的配置如下

编辑vhosts下虚拟主机的配置文件,在location匹配配置中添加如下内容:proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "Upgrade";

具体配置实例如下

server {
    listen       80;
    server_name  域名;
 
    proxy_http_version  1.1;
   #启用支持websocket连接的配置
    proxy_set_header    Upgrade             $http_upgrade;
    proxy_set_header    Connection          "upgrade";
    upstream myweb_backend {
      hash $remote_addr consistent;
      server 10.10.12.108:9001;
      server 10.10.12.109:9001;
    }
    location / {
        proxy_redirect off;
        proxy_set_header Host $http_host;
        proxy_set_header x-real-ip $remote_addr;
        proxy_set_header x-scheme $scheme;
        proxy_pass http://myweb_backend;
        proxy_connect_timeout 60; #配置规避webSocket连接中断
        proxy_read_timeout 600;  #配置规避webSocket连接中断
        proxy_send_timeout 600;  #配置规避webSocket连接中断
    }
 
}

 proxy_set_header    Upgrade   $http_upgrade和proxy_set_header    Connection  "upgrade"也可以配置到location里面 ,配置如下

server {
    listen       80;
    server_name  域名;
    upstream myweb_backend {
      hash $remote_addr consistent;
      server 10.10.12.108:9001;
      server 10.10.12.109:9001;
    }
    location / {
        proxy_redirect off;
        proxy_set_header Host $http_host;
        proxy_set_header x-real-ip $remote_addr;
        proxy_set_header x-scheme $scheme;
        proxy_pass http://myweb_backend;
        proxy_connect_timeout 60; #配置规避webSocket连接中断
        proxy_read_timeout 600; #配置规避webSocket连接中断
        proxy_send_timeout 600;#配置规避webSocket连接中断
        proxy_http_version  1.1;
        #启用支持websocket连接的配置
        proxy_set_header    Upgrade             $http_upgrade;
        proxy_set_header    Connection          "upgrade";
    }
 
}

推荐阅读