node中间层.png
参考文档:https://blog.csdn.net/gu_wen_jie/article/details/82149003

一、搭建简易的nginx负载均衡

1、创建服务器

新建两个js文件,然后分别创建一个服务器,监听不同的端口:

服务器一:

  1. const http = require("http")
  2. http.createServer((req,res)=>{
  3. res.end('8888端口服务器被访问了');
  4. }).listen(8888,()=>{
  5. console.log('服务器启动在8888');
  6. })

服务器二:

  1. const http = require("http")
  2. http.createServer((req,res)=>{
  3. res.end('9999端口服务器被访问了');
  4. }).listen(9999,()=>{
  5. console.log('服务器启动在9999');
  6. })

image.png
但是此时访问地址会发现是乱码的,可以设置一下返回报文的head的content-type:

  1. const http = require("http")
  2. http.createServer((req,res)=>{
  3. res.writeHead(200,{'content-type': 'text/html;charset=utf-8'})
  4. res.end('8888端口服务器被访问了');
  5. }).listen(8888,()=>{
  6. console.log('服务器启动在8888');
  7. })

此时察看,返回正常了。
image.png

2、配置nginx均衡负载

在本地的nginx下的nginx.conf文件下填充下面一段代码

  1. ## 配置localhost的负载均衡
  2. upstream localhost {
  3. server localhost:8888 weight=1; #weight权重越小,权重越高
  4. server localhost:9999 weight=1;
  5. }
  6. server {
  7. listen 80;
  8. server_name localhost;
  9. location /{
  10. proxy_pass http://localhost;
  11. }
  12. }

3、查看结果

reload后,我们去打开监听的地址localhost。多次刷新尝试。
image.png
image.png
我们可以清晰的发现,通过nginx的配置,我们每次进入不同的服务器。这就是负载均衡的理念。在node做中间件的项目中,负载均衡尤为重要,能很好地解决node单线程模式下,同时发送的请求被处理,防止node服务器阻塞卡死。