首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

nginx+spring boot 微服务实现负载均衡

环境准备

项目 JDK1.8 以上版本

准备好 nginx 环境

nginx 配置

nginx 的配置文件在/usr/local/nginx/conf 目录下,配置文件 nginx.conf

配置信息如下:

upstream web_app {

server 192.168.226.150:8089   max_fails=2 fail_timeout=30s;

}

upstream web_app:定义一个名称,随意取名

server + ip:端口 or 域名

在虚拟主机添加如下配置

# 虚拟主机配置

server {

listen       80;

server_name  localhost;

location / {

 #root   html;       #定义服务器的默认根目录位置

 #index  index.html index.htm;

 #反向代理的配置

 #如果后端的服务器返回502,504,执行超时等错误,自动将请求转发到upstream负载均衡中的一台服务器

 #实现故障转移

      proxy_next_upstream http_502 http_504 error timeout invalid_header;

     #将代理服务器收到的用户的信息传到真实服务器上

      proxy_set_header Host  $host;

      proxy_set_header X-Real-IP $remote_addr;

      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# 与上面配置的转发的名称一致

      proxy_pass http://web_app;

}

说明:

server:虚拟主机的名称,一个 HTTP 中可以配置多个 server;

listen:nginx 默认的端口

server_name:nginx 服务的地址, 可以使用域名,多个用空格分隔

proxy_pass :代理路径,一般配置 upstream 后面的名称用于实现负载均衡可以直接配置 ip 进行跳转

nginx.conf 简单的完整配置:

events {

worker_connections 1024;

}

error_log nginx-error.log info;

http {

include mime.types;

default_type application/octet-stream;

sendfile on;

keepalive_timeout 65;

upstream web_app{

server 192.168.226.150:8089 max_fails=2 fail_timeout=30s;

}

server {

listen       80;

server_name  127.0.0.1;

location / {

 root   html;

proxy_pass http://web_app;

 proxy_connect_timeout 3s;

 proxy_read_timeout 5s;

 proxy_send_timeout 3s;

 index  index.html index.htm;

}

error_page   500 502 503 504  /50x.html;

location = /50x.html {

 root   html;

}

}

}

负载均衡测试

完成上面的 Nginx 配置之后,重启启动 Nginx

[root@localhost ~]# /usr/local/nginx/sbin/nginx -s reload

微服务启动:

[root@pertest bin]# sh server.sh restart

访问接口,通过 nginx 的 ip:端口 + 接口后缀地址

通过 nginx 的日志,也可以看到访问成功了

当有多个节点的时候,在 nginx 配置文件里面加上对应的 ip:端口就可以了。

本文作者:柠檬班软件测试(lemonban)——专注于最新最前沿的软件测试技术,解决你的测试技术烦恼,对软件测试感兴趣的朋友赶快关注我们吧!

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20201120A0G4PL00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券