负载均衡主要通过专门的硬件设备或者软件算法实现。通过硬件设备实现的负载均衡效果好、效率高、性能稳定,但是成本较高。而通过软件实现的负载均衡主要依赖于均衡算法的选择和程序的健壮性。均衡算法又主要分为两大类:静态负载均衡算法和动态负载均衡算法。
静态负载均衡算法:主要包括轮询算法、基于比率的加权轮询算法或者基于优先级的加权轮询算法。
动态负载均衡算法:主要包括基于任务量的最少连接优化算法、基于性能的最快响应优先算法、预测算法及动态性能分配算法等。
静态负载均衡算法在一般网络环境下也能表现的比较好,动态负载均衡算法更加适用于复杂的网络环境。
1.基于轮询的负载均衡
每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器 down 掉,能自动剔除。
upstream OrdinaryPolling {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://OrdinaryPolling;
index index.html index.htm index.jsp;
}
}
2.基于比例加权的负载均衡——weight
weight 代表权重, 默认为 1,权重越高被分配的客户端越多
upstream OrdinaryPolling {
ip_hash;
server 127.0.0.1:8080 weight=5;
server 127.0.0.1:8081 weight=2;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://OrdinaryPolling;
index index.html index.htm index.jsp;
}
}
3.基于IP路由的负载均衡——ip_hash
为了保存会话状态。
请求在经过一个服务器处理时,服务器会保存相关的会话信息,比如session,但是该请求如果第一个服务器没处理完,通过nginx轮询到第二个服务器上,那么这个服务器是没有会话信息的。
用户第一次进入一个系统是需要进行登录身份验证的,首先将请求跳转到Tomcat1服务器进行处理,登录信息是保存在Tomcat1 上的,这时候需要进行别的操作,那么可能会将请求轮询到第二个Tomcat2上,那么由于Tomcat2 没有保存会话信息,会以为该用户没有登录,然后继续登录一次,如果有多个服务器,每次第一次访问都要进行登录,这显然是很影响用户体验的。
通常有两种方法解决会话状的问题:
选择一个中间件,将登录信息保存在一个中间件上,这个中间件可以为 Redis 这样的数据库。那么第一次登录,我们将session 信息保存在 Redis 中,跳转到第二个服务器时,我们可以先去Redis上查询是否有登录信息,如果有,就能直接进行登录之后的操作了,而不用进行重复登录。
据客户端的IP地址划分,每次都将同一个 IP 地址发送的请求都分发到同一个 Tomcat 服务器,那么也不会存在 session 共享的问题。
ip_hash 每个请求按访问 ip 的 hash 结果分配,这样每个访客固定访问一个后端服务器。
upstream OrdinaryPolling {
#同一个 IP 地址客户端发送的请求都将分发到同一个服务器进行处理
ip_hash;
server 127.0.0.1:8080 weight=5;
server 127.0.0.1:8081 weight=2;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://OrdinaryPolling;
index index.html index.htm index.jsp;
}
}
4.基于响应时间的负载均衡——fair
fair(第三方),按后端服务器的响应时间来分配请求,响应时间短的优先分配。
upstream OrdinaryPolling {
server 127.0.0.1:8080 weight=5;
server 127.0.0.1:8081 weight=2;
fair;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://OrdinaryPolling;
index index.html index.htm index.jsp;
}
}
5. 基于域名的负载均衡
通过配合location 指令块我们还可以实现对不同域名实现负载均衡。
upstream wordbackend {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
upstream pptbackend {
server 127.0.0.1:8082;
server 127.0.0.1:8083;
}
server {
listen 80;
server_name localhost;
location /word/ {
proxy_pass http://wordbackend;
index index.html index.htm index.jsp;
}
location /ppt/ {
proxy_pass http://pptbackend;
index index.html index.htm index.jsp;
}
}
————Blueicex 2020/2/25 13:01 blueice1980@126.com