当前位置:   article > 正文

Nginx 代理 和负载均衡WebSocket 应用_websocket负载均衡 部署nginx

websocket负载均衡 部署nginx

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必须设置一致

  1. GET /app/websocket/ HTTP/1.1
  2. Host: localhost
  3. Upgrade: websocket
  4. Connection: Upgrade
  5. Sec-WebSocket-Key: dddskkkdsjss
  6. Origin: http://localhost
  7. Sec-WebSocket-Version: 13

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

客户端请求:

  1. GET / HTTP/1.1
  2. Upgrade: websocket
  3. Connection: Upgrade
  4. Host: example.com
  5. Origin: http://example.com
  6. Sec-WebSocket-Key: sN9cRrP/n9NdMgdcy2VJFQ==
  7. Sec-WebSocket-Version: 13


服务器回应:

  1. HTTP/1.1 101 Switching Protocols
  2. Upgrade: websocket
  3. Connection: Upgrade
  4. Sec-WebSocket-Accept: fFBooB7FAkLlXgRSz0BT3v4hq5s=
  5. 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";

具体配置实例如下

  1. server {
  2. listen 80;
  3. server_name 域名;
  4. proxy_http_version 1.1;
  5. #启用支持websocket连接的配置
  6. proxy_set_header Upgrade $http_upgrade;
  7. proxy_set_header Connection "upgrade";
  8. upstream myweb_backend {
  9. hash $remote_addr consistent;
  10. server 10.10.12.108:9001;
  11. server 10.10.12.109:9001;
  12. }
  13. location / {
  14. proxy_redirect off;
  15. proxy_set_header Host $http_host;
  16.         proxy_set_header x-real-ip $remote_addr;
  17.         proxy_set_header x-scheme $scheme;
  18. proxy_pass http://myweb_backend;
  19. proxy_connect_timeout 60; #配置规避webSocket连接中断
  20. proxy_read_timeout 600; #配置规避webSocket连接中断
  21. proxy_send_timeout 600; #配置规避webSocket连接中断
  22. }
  23. }

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

  1. server {
  2. listen 80;
  3. server_name 域名;
  4. upstream myweb_backend {
  5. hash $remote_addr consistent;
  6. server 10.10.12.108:9001;
  7. server 10.10.12.109:9001;
  8. }
  9. location / {
  10. proxy_redirect off;
  11. proxy_set_header Host $http_host;
  12.         proxy_set_header x-real-ip $remote_addr;
  13.         proxy_set_header x-scheme $scheme;
  14. proxy_pass http://myweb_backend;
  15. proxy_connect_timeout 60; #配置规避webSocket连接中断
  16. proxy_read_timeout 600; #配置规避webSocket连接中断
  17. proxy_send_timeout 600;#配置规避webSocket连接中断
  18. proxy_http_version 1.1;
  19. #启用支持websocket连接的配置
  20. proxy_set_header Upgrade $http_upgrade;
  21. proxy_set_header Connection "upgrade";
  22. }
  23. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/448465
推荐阅读
相关标签
  

闽ICP备14008679号