参考文档:https://blog.csdn.net/gu_wen_jie/article/details/82149003
一、搭建简易的nginx负载均衡
1、创建服务器
新建两个js文件,然后分别创建一个服务器,监听不同的端口:
服务器一:
const http = require("http")
http.createServer((req,res)=>{
res.end('8888端口服务器被访问了');
}).listen(8888,()=>{
console.log('服务器启动在8888');
})
服务器二:
const http = require("http")
http.createServer((req,res)=>{
res.end('9999端口服务器被访问了');
}).listen(9999,()=>{
console.log('服务器启动在9999');
})
但是此时访问地址会发现是乱码的,可以设置一下返回报文的head的content-type:
const http = require("http")
http.createServer((req,res)=>{
res.writeHead(200,{'content-type': 'text/html;charset=utf-8'})
res.end('8888端口服务器被访问了');
}).listen(8888,()=>{
console.log('服务器启动在8888');
})
2、配置nginx均衡负载
在本地的nginx下的nginx.conf文件下填充下面一段代码
## 配置localhost的负载均衡
upstream localhost {
server localhost:8888 weight=1; #weight权重越小,权重越高
server localhost:9999 weight=1;
}
server {
listen 80;
server_name localhost;
location /{
proxy_pass http://localhost;
}
}
3、查看结果
reload后,我们去打开监听的地址localhost。多次刷新尝试。
我们可以清晰的发现,通过nginx的配置,我们每次进入不同的服务器。这就是负载均衡的理念。在node做中间件的项目中,负载均衡尤为重要,能很好地解决node单线程模式下,同时发送的请求被处理,防止node服务器阻塞卡死。