一、nginx配置ip_hash负载均衡策略
nginx默认的负载均衡策略为轮询,某些场景需要使用ip_hash负载策略,即:同一个ip地址,永远访问nginx后面同一台tomcat。配置示例如下,主要是设置ip_hash:
upstream www.abc.com{
ip_hash;
server 202.119.11.23:8899;
server 172.168.10.99:8899;
server 202.119.11.121:8899;
}
二、配置后如何验证ip_hash有没有生效
1、需要打开nginx的access log查看请求来自哪个ip、访问哪个负载。
(1)首先,配置access日志格式;
(2)其次,打开access日志;
(3)验证后注意关闭access日志。
2、完整示例如下
#表示使用几个nginx线程,一般取值为cpu个数-1
worker_processes 1;
#是否打开error日志,及error日志路径
error_log logs/error.log;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
client_max_body_size 2048m;
#access日志格式
log_format log_custom '$remote_addr - $remote_user [$time_local] "$server_addr" "$upstream_addr" $status "$request" --- '
'$body_bytes_sent --- "$http_referer" ---'
'"$http_user_agent" --- "$http_x_forwarded_for"';
#开启access日志,及指定日志格式。注意:开始access日志方式是如下方式,并不是access_log on方式;关闭access日志方式是:access_log off;
access_log logs/access.log log_custom;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
upstream www.abc.com{
ip_hash;
server 202.119.11.23:8899;
server 172.168.10.99:8899;
server 202.119.11.121:8899;
}
server {
listen 80;
server_name localhost;
location ^~ /api-base {
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Connection "";
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://www.abc.com;
}
}
}
3、对应的日志效果
三、ip_hash算法对应的java代码示例
package com.nation.net;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* nginx ip_hash算法示例
*
*/
public class IpHashLoadBalancer {
private final List<String> servers;
private final AtomicInteger currentIndex = new AtomicInteger(0);
public IpHashLoadBalancer(List<String> servers) {
this.servers = servers;
}
public String selectServer(String clientIp) {
try {
// 将客户端IP地址转换为字节数组
byte[] ipBytes = InetAddress.getByName(clientIp).getAddress();
// 使用MD5算法计算哈希值
byte[] hashBytes = java.security.MessageDigest.getInstance("MD5").digest(ipBytes);
// 将哈希值转换为正整数
int hash = 0;
for (byte b : hashBytes) {
hash <<= 8;
hash ^= (b & 0xFF);
}
// 使用哈希值选择服务器
int serverIndex = Math.abs(hash) % servers.size();
// 如果有必要,可以在这里实现一个轮询机制,使得下一次请求可能选择另一个服务器
// currentIndex.incrementAndGet();
// int serverIndex = currentIndex.getAndIncrement() % servers.size();
return servers.get(serverIndex);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
//负载地址
List<String> servers = Arrays.asList("202.119.11.23","172.168.10.99","202.119.11.121");
IpHashLoadBalancer loadBalancer = new IpHashLoadBalancer(servers);
// 假设客户端IP地址
String clientIp = "172.168.10.187";
// 选择服务器
String selectedServer = loadBalancer.selectServer(clientIp);
System.out.println("Selected server: " + selectedServer);
}
}