之所以用到nginx来做负载均衡,是因为我们可以通过简单的配置就能达到双机,多机负载均衡的目的;另外,如 负载均衡之Ocelot 所述 网关 API ,如果一个服务群的 网关 挂掉了,那整个服务都无法工作。因此我们可能需要将 网关API 布署在多台机器上,并做负载均衡。
以下是我在linux机上对 一个网关做负载的尝试:
nginx的配置如下:
#GateWay API_1
server {
listen 8104;
location / {
proxy_pass http://localhost:5101;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
}
}
#GateWay API_2
server {
listen 8102;
location / {
proxy_pass http://localhost:5102;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
}
}
#GateWay API_3
server {
listen 8103;
location / {
proxy_pass http://localhost:5103;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
}
}
#Ocelot api gateway Load Balance
upstream ocelot {
server localhost:8104;
server localhost:8102;
server localhost:8103;
}
server {
listen 8101;
location / {
proxy_pass http://ocelot ;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
}
}
server {
listen 8104;
location / {
proxy_pass http://localhost:5101;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
}
}
#GateWay API_2
server {
listen 8102;
location / {
proxy_pass http://localhost:5102;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
}
}
#GateWay API_3
server {
listen 8103;
location / {
proxy_pass http://localhost:5103;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
}
}
#Ocelot api gateway Load Balance
upstream ocelot {
server localhost:8104;
server localhost:8102;
server localhost:8103;
}
server {
listen 8101;
location / {
proxy_pass http://ocelot ;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
}
}
以上我将网关API布署了 3 套,分别是
localhost:8102
localhost:8103
localhost:8104
来代表布署在3台机器上
上游服务器端口为 8101。我们还可以根据3台机器的好坏程度来做权重,比如第一台CPU配置最高,配置如下
upstream ocelot {
server localhost:8104 weight=2;
server localhost:8104 weight=2;
server localhost:8102 weight=1;
server localhost:8103 weight=1;
}
这样 8104 那台,如果有4次请求,它会接收2次
可以看到多次访问,每次指向的内网端口是不一样的
综上所述
1. 单台机子用会 ocelot api gateway 对高频调用的 API 做负载(ocelot当然也可以做多机负载均衡);
2. 在两台服务器上布署好之后,用ngnix配置,将两台运输挂号服务器做负载均衡;