所需软件:
网络要求:
下载并解压Tomcat到不同目录,例如:
C:\tomcat1
C:\tomcat2
修改每个Tomcat的端口号(避免冲突):
conf/server.xml
xml
<Server port="8005" shutdown="SHUTDOWN"> <!-- 例如:8005, 8006 -->
<Connector port="8080" protocol="HTTP/1.1" ... /> <!-- 例如:8080, 8081 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /> <!-- 例如:8009, 8010 -->
启动所有Tomcat实例,确保都能独立访问:
http://localhost:8080
http://localhost:8081
下载Nginx for Windows并解压(如C:\nginx
)
修改conf/nginx.conf
配置文件:
http {
upstream tomcat_cluster {
# 配置Tomcat服务器列表
server 127.0.0.1:8080 weight=1;
server 127.0.0.1:8081 weight=1;
# 可以添加更多Tomcat实例
# 负载均衡策略(可选):
# least_conn; # 最少连接
# ip_hash; # IP哈希
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://tomcat_cluster;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
启动Nginx:
cd C:\nginx
start nginx
访问http://localhost
,Nginx会将请求分发到不同的Tomcat实例
可以通过以下方式验证:
如果应用需要会话保持,可以使用ip_hash
策略:
upstream tomcat_cluster {
ip_hash;
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
或者配置Tomcat集群会话复制。
Nginx可以自动检测后端服务器状态:
upstream tomcat_cluster {
server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
server 127.0.0.1:8081 max_fails=3 fail_timeout=30s;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
root /path/to/static/files;
expires 30d;
}
Nginx无法启动:
nginx -t
502 Bad Gateway:
性能问题:
Windows服务化:
Nginx状态监控:
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
日志分析:
通过以上配置,您可以在Windows系统下实现Nginx+Tomcat的负载均衡,提高应用的可用性和性能。