相关文章:
Nginx 官方文档:HTTP Load Balancing
在CentOS 1804 中设置 Apache Tomcat 9.0.12 开机自启
前言:
本次使用 Nginx 源码构建安装 Nginx。
Nginx 安装及使用参见相关文章。
使用 tomcat 作为作为效果展示(使用 tomcat 需要安装 JDK)。
- tomcat 配置:
端口相同会导致运行时端口占用异常。tomcat服务器名称
shutdown port
http port
redirectPort port
AJP port
tomcat9-0(服务器 0)
8005(默认)
8080(默认)
8443(默认)
8009(默认)
tomcat9-1(服务器 1)
8006
8081
8444
8010
tomcat9-2(备份服务器)
8007
8082
8445
8011
- 为了区分负载均衡的效果,修改 tomcat 根目录中 webapps/ROOT/index.jsp:
将 title 修改为对应 tomcat 的名字。...... <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>tomcat9-0</title> <link href="favicon.ico" rel="icon" type="image/x-icon" /> <link href="favicon.ico" rel="shortcut icon" type="image/x-icon" /> <link href="tomcat.css" rel="stylesheet" type="text/css" /> </head> ......
- 端口配置:
注意不要重复打开同一个端口。firewall-cmd --zone=public --add-port=80/tcp --permanent firewall-cmd --zone=public --add-port=8080/tcp --permanent firewall-cmd --zone=public --add-port=8081/tcp --permanent firewall-cmd --zone=public --add-port=8082/tcp --permanent firewall-cmd --reload firewall-cmd --list-all
- 首先直接访问各 tomcat ,查看效果:
- 配置 Nginx 负载均衡:
在 http 中增加:vim /usr/local/nginx/conf/nginx.conf
修改 server:upstream tomcatBalancing { server 127.0.0.1:8080; server 127.0.0.1:8081; server 127.0.0.1:8082 backup; }
location / { proxy_pass http://tomcatBalancing; #root html; #index index.html index.htm; }
- 重启 Nginx,访问 Nginx:
第一次访问:
刷新:
可以观察到 title 发生变化,重复刷新,title 在 tomcat9-0 与 tomcat9-1 中切换。
- 模拟故障 1:
停止 tomcat9-0,重复访问一直是 tomcat9-1。
停止 tomcat9-1 同理。
- 模拟故障 2:
停止 tomcat9-0、tomcat9-1,重复访问一直是 tomcat9-2。
-
服务器权重:
默认情况下,NGINX使用Round Robin方法根据权重在组中的服务器之间分配请求。指令的weigth
参数server
设置服务器的权重; 默认值为1。
设置 tomcat9-0 权重为5:upstream tomcatBalancing { server 127.0.0.1:8080 weight=5; server 127.0.0.1:8081; server 127.0.0.1:8082 backup; }
重启 Nginx 后,刷新查看效果。
-
启用持久性会话:
由于负载均衡,用户访问时,一直在 服务器中 切换。
NGINX Plus识别用户会话并将给定会话中的所有请求路由到同一上游服务器中。