天天看點

Nginx的負載均衡方案詳解Nginx的負載均衡方案詳解

版權聲明:本文為部落客chszs的原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/chszs/article/details/43203465

Nginx的負載均衡方案詳解

作者:chszs,轉載需注明。部落格首頁:

http://blog.csdn.net/chszs

Nginx的負載均衡方案有:

1、輪詢

輪詢即Round Robin,根據Nginx配置檔案中的順序,依次把用戶端的Web請求分發到不同的後端伺服器。

配置的例子如下:

http{
    upstream sampleapp {
        server <<dns entry or IP Address(optional with port)>>;
        server <<another dns entry or IP Address(optional with port)>>;
    }
    ....
    server{
       listen 80;
       ...
       location / {
          proxy_pass http://sampleapp;
       }  
    }
           

上面隻有1個DNS入口被插入到upstream節,即sampleapp,同樣也在後面的proxy_pass節重新提到。

2、最少連接配接

Web請求會被轉發到連接配接數最少的伺服器上。

http{
    upstream sampleapp {
        least_conn;
        server <<dns entry or IP Address(optional with port)>>;
        server <<another dns entry or IP Address(optional with port)>>;
    }
    ....
    server{
       listen 80;
       ...
       location / {
          proxy_pass http://sampleapp;
       }  
    }
           

上面的例子隻是在upstream節添加了least_conn配置。其它的配置同輪詢配置。

3、IP位址哈希

前述的兩種負載均衡方案中,同一用戶端連續的Web請求可能會被分發到不同的後端伺服器進行處理,是以如果涉及到會話Session,那麼會話會比較複雜。常見的是基于資料庫的會話持久化。要克服上面的難題,可以使用基于IP位址哈希的負載均衡方案。這樣的話,同一用戶端連續的Web請求都會被分發到同一伺服器進行處理。

http{
    upstream sampleapp {
        ip_hash;
        server <<dns entry or IP Address(optional with port)>>;
        server <<another dns entry or IP Address(optional with port)>>;
    }
    ....
    server{
       listen 80;
       ...
       location / {
          proxy_pass http://sampleapp;
       }  
    }
           

上面的例子隻是在upstream節添加了ip_hash配置。其它的配置同輪詢配置。

4、基于權重的負載均衡

基于權重的負載均衡即Weighted Load Balancing,這種方式下,我們可以配置Nginx把請求更多地分發到高配置的後端伺服器上,把相對較少的請求分發到低配伺服器。

http{
    upstream sampleapp {
        server <<dns entry or IP Address(optional with port)>> weight=2;
        server <<another dns entry or IP Address(optional with port)>>;
    }
    ....
    server{
       listen 80;
       ...
       location / {
          proxy_pass http://sampleapp;
       }
  }
           

上面的例子在伺服器位址和端口後weight=2的配置,這意味着,每接收到3個請求,前2個請求會被分發到第一個伺服器,第3個請求會分發到第二個伺服器,其它的配置同輪詢配置。

還要說明一點,基于權重的負載均衡和基于IP位址哈希的負載均衡可以組合在一起使用。