日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Nginx >内容正文

Nginx

细说 Nginx: 负载均衡 Load Balance

發布時間:2023/12/8 Nginx 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 细说 Nginx: 负载均衡 Load Balance 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

細說 Nginx: 負載均衡 Load Balance

文章目錄

  • 細說 Nginx: 負載均衡 Load Balance
  • 準備服務
  • 負載均衡配置項
    • 負載均衡策略
    • 更多配置項
  • 示例
    • ip_hash
    • 輪詢 + 權重
  • 參考連接
  • 完整代碼示例

準備服務

首先我們先準備三個后端服務,起在 8081~8083 端口上

  • server.js
const express = require('express');const createServer = (ports) => {const countMap = {}; // port => countports.forEach((port, i) => {const id = i + 1;const app = express();let count = 0;app.get('/', (req, res) => {count += 1;countMap[id] = count;res.send({server: id,count: countMap,});});app.listen(port, () => {console.log(`server${id} listen on http://localhost:${port}`);});}); };createServer([8081, 8082, 8083]);

我們使用 countMap 來記錄每個服務響應請求的次數

負載均衡配置項

接下來是 nginx 的配置項,核心的指令是 upstream

http {upstream hello_server {server localhost:8081;server localhost:8082;server localhost:8083;}server {listen 8999;server_name localhost;location / {proxy_pass http://hello_server;}} }

我們在 http 塊里面添加 upstream 塊,upstream 塊內部再用 server 聲明候選服務的域;最后再將 8999 代理到該服務上能夠實現負載均衡

負載均衡策略

默認的情況下 nginx 采用輪詢每個單體服務的方式,我們也可以指定負載策略

  • 最少連接數優先(least connection)
upstream hello_server {least_conn;# servers ... }

改策略可以從連接數量上平衡請求

  • ip 映射
upstream hello_server {ip_hash;# servers ... }

有些時候需要保證同一個 client 持續跟同一個 server 對接(可能使用 session 持久化等),這時候就使用 ip_hash 來保證多次連接使用同一個服務器

更多配置項

nginx 還提供了更多關于負載均衡的配置項,例如為 server 配置權重(weight)、server 的健康檢查(失敗次數限制 max_fails、超時檢測 fail_timeout 等),需要用到再去配配看

傳送門:Using nginx as HTTP load balancer - Health checks

示例

下面我們演示幾個例子,直接使用上面的配置項并稍微做一點點的修改

ip_hash

upstream hello_server {ip_hash;server localhost:8081;server localhost:8082;server localhost:8083; }

使用 ip_hash 之后我們可以看到多次請求之后一直都是同一個 server 被選中

輪詢 + 權重

upstream hello_server {server localhost:8081 weight=3;server localhost:8082;server localhost:8083; }

默認的輪詢策略下同時為 server:8081 加上權重 3,可以看到連接的處理次數大致是其他服務的三倍


參考連接

TitleLink
Using nginx as HTTP load balancerhttps://nginx.org/en/docs/http/load_balancing.html

完整代碼示例

https://github.com/superfreeeee/Blog-code/tree/main/deployment/nginx/nginx_detail_load_balancer

總結

以上是生活随笔為你收集整理的细说 Nginx: 负载均衡 Load Balance的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。