Nginx负载均衡是一种用于分发网络流量的技术。它可以将传入的请求均匀地分发到多个服务器,以提高系统的性能和可靠性。Nginx是一个开源的高性能Web服务器,它还可以用作反向代理和HTTP缓存。通过使用Nginx负载均衡,您可以实现高可用性和可扩展性,以满足大量流量的需求。
一、Nginx 负载均衡算法
1. 轮询(Round Robin):默认的负载均衡算法,按照服务器列表的顺序依次分发请求。
2. IP哈希(IP Hash):根据客户端的IP地址进行哈希计算,将同一个IP的请求分发到同一台服务器上。
3. 最少连接(Least Connections):将请求分发到当前连接数最少的服务器上。
4. 加权轮询(Weighted Round Robin):根据服务器的权重分配请求,权重越高的服务器获得更多的请求。
5. 加权最少连接(Weighted Least Connections):根据服务器的权重和当前连接数,动态调整请求分发的权重。
二、 Nginx负载均衡配置
1.安装 nginx
[root@localhost ~]# yum install yum-utils
[root@localhost ~]# vim /etc/yum.repos.d/nginx.repo[nginx-stable] name=nginx stable repo baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck=1 enabled=1 gpgkey=https://nginx.org/keys/nginx_signing.key module_hotfixes=true [nginx-mainline] name=nginx mainline repo baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/ gpgcheck=1 enabled=0 gpgkey=https://nginx.org/keys/nginx_signing.key module_hotfixes=true[root@localhost ~]# yum -y install nginx
2.安装Tomcat & JDK
[root@localhost ~]# yum -y install lrzsz
[root@localhost ~]# tar xzf jdk-11.0.16_linux-x64_bin.tar.gz -C /usr/local/
[root@localhost ~]# cd /usr/local/
[root@localhost local]# mv jdk-11.0.16 java
[root@localhost local]# vim /etc/profile.d/jdk.sh
export JAVA_HOME=/usr/local/java export PATH=$JAVA_HOME/bin:$JAVA_HOME/jre/bin:$PATH export CLASSPATH=.:$JAVA_HOME/lib:$JAVA_HOME/jre/lib:$JAVA_HOME/lib/tools.jar
[root@localhost local]# source /etc/profile.d/jdk.sh
[root@localhost opt]# tar -zxvf apache-tomcat-9.0.79.tar.gz -C /opt/
[root@localhost ~]# cd /opt
[root@localhost opt]# mv apache-tomcat-9.0.79 tomcat
[root@localhost opt]# vim /etc/profile
export TOMCAT_HOME=/opt/tomcat
[root@localhost local]# source /etc/profile
[root@localhost ~]# cd /opt/tomcat/webapps/ROOT
[root@localhost ROOT]# rm -rf ./*
编写 index.html 便于测试,内容如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
Hello Web1!
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
Hello Web2!
</body>
</html>
3.Nginx负载均衡配置
[root@localhost ~]# vim /etc/nginx/nginx.conf
[root@localhost ~]# vim /etc/nginx/conf.d/default.conf