1. 程式人生 > >基於Nginx的Wesocket負載均衡

基於Nginx的Wesocket負載均衡

負載均衡 nginx wesocket

分享一個基於NginxWesocket的負載均衡。

1.在mac電腦安裝nginx

brew install nginx

2.安裝完成以後nginx的配置文件路徑

/usr/local/etc/nginx/nginx.conf

3.編輯配置文件進行配置

在http塊

新增配置

#gzip on;

map $http_upgrade $connection_upgrade {

default upgrade;

‘‘ close;

}

upstream ws_server {

server qa.server.com:2048;

server qa.server.ai:2048;

}


server {

listen 2048;

server_name localhost;


location /ws {

proxy_pass http://ws_server/ws;

proxy_redirect off;

proxy_http_version 1.1;

proxy_set_header Upgrade $http_upgrade;

proxy_set_header Connection "upgrade";

}

}


簡要說明一下,nginx監聽2048端口,把請求轉發到qa.server.h,qa.server.test

客戶端通過這個地址 連接:ws://localhost:2048/ws


之前一直有疑問,為什麽ws協議要通過http協議來代理?


ws 協議的握手部分是借用http協議了,在握手完成以後進行了協議的切換(header部分的upgrade)。

這個查看網絡連接


    1. Request URL:

      ws://localhost:2048/ws

    2. Request Method:

      GET

    3. Status Code:

    4. 101 Switching Protocols


  1. Response Headersview source

    1. Connection:

      upgrade

    2. Date:

      Fri, 15 Sep 2017 01:48:28 GMT

    3. sec-websocket-accept:

      r+ZclgKaM7r9b6RklYinaGUcvwE=

    4. Server:

      nginx/1.12.1

    5. upgrade:

      websocket

  2. Request Headersview source

    1. Accept-Encoding:

      gzip, deflate, br

    2. Accept-Language:

      en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4

    3. Cache-Control:

      no-cache

    4. Connection:

      Upgrade

    5. Host:

      localhost:2048

    6. Origin:

      http://localhost:8000

    7. Pragma:

      no-cache

    8. Sec-WebSocket-Extensions:

      permessage-deflate; client_max_window_bits

    9. Sec-WebSocket-Key:

      yoh2s/VG9x099oJEoP4FNA==

    10. Sec-WebSocket-Version:

      13

    11. Upgrade:

      websocket

    12. User-Agent:

      Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36





本文出自 “12355380” 博客,請務必保留此出處http://12365380.blog.51cto.com/12355380/1965511

基於Nginx的Wesocket負載均衡