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

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > Nginx >内容正文

Nginx

细说 Nginx: 负载均衡 Load Balance

發(fā)布時(shí)間:2023/12/8 Nginx 70 豆豆
生活随笔 收集整理的這篇文章主要介紹了 细说 Nginx: 负载均衡 Load Balance 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

細(xì)說(shuō) Nginx: 負(fù)載均衡 Load Balance

文章目錄

  • 細(xì)說(shuō) Nginx: 負(fù)載均衡 Load Balance
  • 準(zhǔn)備服務(wù)
  • 負(fù)載均衡配置項(xiàng)
    • 負(fù)載均衡策略
    • 更多配置項(xiàng)
  • 示例
    • ip_hash
    • 輪詢(xún) + 權(quán)重
  • 參考連接
  • 完整代碼示例

準(zhǔn)備服務(wù)

首先我們先準(zhǔn)備三個(gè)后端服務(wù),起在 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 來(lái)記錄每個(gè)服務(wù)響應(yīng)請(qǐng)求的次數(shù)

負(fù)載均衡配置項(xiàng)

接下來(lái)是 nginx 的配置項(xiàng),核心的指令是 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;}} }

我們?cè)?http 塊里面添加 upstream 塊,upstream 塊內(nèi)部再用 server 聲明候選服務(wù)的域;最后再將 8999 代理到該服務(wù)上能夠?qū)崿F(xiàn)負(fù)載均衡

負(fù)載均衡策略

默認(rèn)的情況下 nginx 采用輪詢(xún)每個(gè)單體服務(wù)的方式,我們也可以指定負(fù)載策略

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

改策略可以從連接數(shù)量上平衡請(qǐng)求

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

有些時(shí)候需要保證同一個(gè) client 持續(xù)跟同一個(gè) server 對(duì)接(可能使用 session 持久化等),這時(shí)候就使用 ip_hash 來(lái)保證多次連接使用同一個(gè)服務(wù)器

更多配置項(xiàng)

nginx 還提供了更多關(guān)于負(fù)載均衡的配置項(xiàng),例如為 server 配置權(quán)重(weight)、server 的健康檢查(失敗次數(shù)限制 max_fails、超時(shí)檢測(cè) fail_timeout 等),需要用到再去配配看

傳送門(mén):Using nginx as HTTP load balancer - Health checks

示例

下面我們演示幾個(gè)例子,直接使用上面的配置項(xiàng)并稍微做一點(diǎn)點(diǎn)的修改

ip_hash

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

使用 ip_hash 之后我們可以看到多次請(qǐng)求之后一直都是同一個(gè) server 被選中

輪詢(xún) + 權(quán)重

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

默認(rèn)的輪詢(xún)策略下同時(shí)為 server:8081 加上權(quán)重 3,可以看到連接的處理次數(shù)大致是其他服務(wù)的三倍


參考連接

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

總結(jié)

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

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。