一:下载Nginx
Nginx官网中下载,我这些下载的是Windoiws环境包 nginx-1.23.3
二:后端服务准备
我选用的是Java后端服务,当然如果你是前端程序员或者全栈开发可以选择nodejs来搭建服务,这里仅用作测试使用。
Controller接口
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class LoadBalanceController {
@Autowired
private ILoadBalanceService loadBalanceService;
@GetMapping("/test")
public Object whoAmI(){
return loadBalanceService.whoAmI();
}
}
Service层接口及实现类
public interface ILoadBalanceService {
Object whoAmI();
}
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class LoadBalanceServiceImpl implements ILoadBalanceService {
@Value("${server.port}")
public Integer serverPort;
@Override
public Object whoAmI() {
ServerInfo info = new ServerInfo();
info.setCode(200);
info.setServer("Server#5");
info.setPort(serverPort);
return info;
}
}
配置文件
## log
debug = true
logging.level.org.springframework.web = DEBUG
# log
logging.path=./log
# encoding
spring.http.encoding.charset=UTF-8
spring.http.encoding.force=true
server.servlet.context-path=/load_balance
server.port=8885
pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.12</version>
<relativePath/>
</parent>
<groupId>com.lemon</groupId>
<artifactId>load-balance</artifactId>
<version>1.0-Alpha</version>
<name>Load Balance</name>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
此处我使用指定配置文件的方式,分别启动了五分后端代码,端口分别是8881,8882,8883,8884,8885,使用浏览器单独访问五个后端Java服务均可以访问接口。
三:配置nginx.conf
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
upstream polling {
server 192.168.3.99:8881 max_fails=3 fail_timeout=30s;
server 192.168.3.99:8882 max_fails=3 fail_timeout=30s;
server 192.168.3.99:8883 max_fails=3 fail_timeout=30s;
server 192.168.3.99:8884 max_fails=3 fail_timeout=30s;
server 192.168.3.99:8885 max_fails=3 fail_timeout=30s;
}
server {
listen 88;
server_name 192.168.3.180;
location /load_balance {
proxy_pass http://polling/load_balance;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
使用upstream声明一组集群服务,后续使用轮询策略时Nginx会从这一组服务中根据配置的参数选择其中一个服务,本次测试采用轮询策略并且实现剔除宕机的服务功能。
upstream声明中的参数简介
upstream polling { }
其中 “polling”是我为这组集群服务起的一个名字,这个名字可以按照个人喜好随意起名
server 192.168.3.99:8881 max_fails=3 fail_timeout=30s;
其中server声明一个服务,其后紧跟一个服务的地址,max_fails声明无响应多少次剔除此服务,fail_timeout声明剔除多长时间后再次恢复此服务的发文,如果恢复后经过max_fails次无响应会再次会剔除出集群队列fail_timeout秒,依次循环直到服务可用为止。当然max_fails和fail_timeout你可以不用配置,使用默认值吗,如 server 192.168.3.99:8881; 此时 max_fails默认为3次,fail_timeout默认为10秒。
配置完成后启动nginx,访问接口我们可以看到会在这5个服务中轮询访问,当其中一个服务不可用时会被切换到下一个服务,当服务恢复时会可选队列的头部。
server声明中的参数简介
在Nginx的配置文件 nginx.conf
中,server
参数通常用于定义服务器块(server block)或虚拟主机的配置。每个 server
块包含了一组指令,用于配置特定的虚拟主机或服务器的行为。以下是 server
参数的一些重要功能:
-
虚拟主机配置:
server
参数允许您定义多个虚拟主机,每个虚拟主机可以监听不同的域名或IP地址,并提供不同的Web服务。这允许您在同一Nginx实例上托管多个网站或应用程序。 -
监听端口和IP地址:通过
listen
指令,您可以指定Nginx服务器块监听的端口和IP地址。这允许您将请求分发到不同的虚拟主机,甚至可以监听不同的网络接口。 -
域名绑定:您可以使用
server_name
指令定义虚拟主机的域名或主机名。这允许Nginx知道如何处理来自不同域名的请求,从而将请求路由到适当的虚拟主机。 -
SSL/TLS配置:
server
参数允许您配置SSL/TLS加密,包括指定SSL证书和其他相关选项,以提供安全的HTTPS连接。 -
请求处理:在
server
块中,您可以配置一系列指令来定义如何处理请求,包括代理请求、缓存、限制访问等等。这允许您定义虚拟主机的行为,以满足应用程序的需求。 -
日志记录:您可以配置日志记录选项,以指定服务器块的访问日志和错误日志的位置和格式。这有助于监控和排查问题。
-
反向代理:如果您希望Nginx充当反向代理服务器,您可以在
server
块中配置代理相关的指令,如proxy_pass
。这允许Nginx将请求代理给后端服务器,以实现负载均衡和缓存等功能。 -
缓存配置:您可以配置Nginx服务器块以启用HTTP缓存,以加速静态资源的传输,减轻后端服务器的负担。
-
访问控制:使用
location
块和其他相关指令,您可以定义如何控制访问到特定URL路径或资源。这包括允许/拒绝访问、基本身份验证等。
总之,server
参数用于定义Nginx服务器块的配置,允许您按需配置虚拟主机或服务器的行为,以满足不同应用程序和网站的需求。您可以在一个 nginx.conf
文件中定义多个 server
块,以支持多个虚拟主机。
此处我们使用反向代理proxy_pass
声明后端服务,引入upstream polling { } 中配置的后端服务地址,nginx在检测到polling(我们声明的一组集群服务地址)后会替换成upstream内的其中一个server,其中具体选择那个server就是按照我们的配置来选择了,此处我们使用轮询策略。
四:统计轮询次数
为了更直观的看到效果,我们再写一个统计功能,统计共计访问次数以及每台服务器分配的数量,这样我们可以更直观感受到效果。
实现代码
import org.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class StartMain {
public static void main(String[] args) {
// 统计项
int Server1 = 0;
int Server2 = 0;
int Server3 = 0;
int Server4 = 0;
int Server5 = 0;
// 处理
String getUrl = "http://192.168.3.180:88/load_balance/api/test";
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(getUrl);
try {
httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
httpGet.setHeader("Accept","application/json");
for (int i = 0; i < 500; i++) {
Thread.sleep(100);
HttpResponse response = httpClient.execute(httpGet);
// 处理响应
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity, "UTF-8");
JSONObject jsonObject = new JSONObject(responseBody);
int port = jsonObject.getInt("port");
System.out.println(port);
if (8881 == port){
Server1 ++;
} else if (8882 == port) {
Server2 ++;
} else if (8883 == port) {
Server3 ++;
} else if (8884 == port) {
Server4 ++;
} else if (8885 == port) {
Server5 ++;
}
}
System.out.println("Server#1,2,3,4,5 分别被分配次数:" + Server1 +","+ Server2 +","+ Server3 +","+ Server4 +","+ Server5 );
}catch (Exception ex){
ex.printStackTrace();
}
}
}
需要导入json的maven坐标
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
使用如上代码我们跑500轮请求,可见请求被平均分配,每一个服务被平均分配100次。
此处就不在演示服务宕机的情况了,大家可以搭建起来自己测试一下。
五:权重轮询
修改的upstream polling { } 文件
加权重关键字:weight,默认值为1。
对8881,8882,8883,8884,8885分别加权5,4,3,2,1 共计权重15,也就是说在15次请求中,5次分配给8881,4次分配给8882,以此类推。
修改后的upstream文件如下:
upstream polling {
server 192.168.3.99:8881 weight=5 max_fails=3 fail_timeout=30s;
server 192.168.3.99:8882 weight=4 max_fails=3 fail_timeout=30s;
server 192.168.3.99:8883 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.3.99:8884 weight=2 max_fails=3 fail_timeout=30s;
server 192.168.3.99:8885 weight=1 max_fails=3 fail_timeout=30s;
}
其他地方不变,我们修改代码内循环次数为 (5+4+3+2+1)*100 = 1500次,最终统计结果分配比例为5:4:3:2:1,如下图: