欢迎光临殡葬网
详情描述

一、架构设计

用户请求 → Nginx(负载均衡) → Tomcat集群(多实例) → Redis(共享会话)

二、环境准备

1. 软件版本

  • Windows 10/11 或 Windows Server
  • Nginx 1.24+ 官网下载
  • Tomcat 9.0+ 官网下载
  • Redis for Windows 微软版本
  • JDK 8/11/17

2. 目录结构建议

C:\cluster\
├── nginx\
├── tomcat1\
├── tomcat2\
├── redis\
└── webapp\  # 你的Web项目

三、详细安装配置步骤

1. Redis安装配置

安装:

下载Redis for Windows 解压到 C:\cluster\redis 修改配置文件 redis.windows.conf
# 绑定所有IP,允许远程连接
bind 0.0.0.0

# 端口号
port 6379

# 设置密码(可选)
requirepass yourpassword

# 持久化设置
save 900 1
save 300 10
save 60 10000

# 最大内存
maxmemory 256mb
maxmemory-policy allkeys-lru

启动Redis:

# 方式1:命令行启动
cd C:\cluster\redis
redis-server.exe redis.windows.conf

# 方式2:安装为Windows服务
redis-server.exe --service-install redis.windows.conf --service-name RedisCluster
net start RedisCluster

2. Tomcat集群配置

准备两个Tomcat实例:

# 复制Tomcat文件夹
xcopy C:\cluster\tomcat1 C:\cluster\tomcat2 /E /I

修改Tomcat配置:

1) 修改端口(避免冲突)

tomcat1/conf/server.xml

<!-- 修改以下端口 -->
<Server port="8005" shutdown="SHUTDOWN">

<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />

<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

tomcat2/conf/server.xml

<Server port="8006" shutdown="SHUTDOWN">

<Connector port="8081" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8444" />

<Connector port="8010" protocol="AJP/1.3" redirectPort="8444" />

2) 配置Redis会话共享

添加依赖到 tomcat1/lib/tomcat2/lib/

  • tomcat-redis-session-manager
  • jedis-3.6.0.jar
  • commons-pool2-2.9.0.jar

修改 conf/context.xml(两个Tomcat都改):

<Context>
    <!-- Redis Session Manager -->
    <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
    <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
             host="localhost"
             port="6379"
             password="yourpassword"
             database="0"
             maxInactiveInterval="1800"
             sessionPersistPolicies="SAVE_ON_CHANGE"
             sentinelMaster=""
             sentinels=""
             timeout="2000"
             />
</Context>

3. Nginx负载均衡配置

修改 nginx/conf/nginx.conf

http {
    # 配置上游服务器(Tomcat集群)
    upstream tomcat_cluster {
        # ip_hash;  # 会话保持(可选)
        # least_conn;  # 最少连接(可选)

        # 权重配置 weight=数字,数字越大权重越高
        server localhost:8080 weight=1 max_fails=3 fail_timeout=30s;
        server localhost:8081 weight=1 max_fails=3 fail_timeout=30s;

        # 保持连接设置
        keepalive 32;
    }

    # 启用gzip压缩
    gzip on;
    gzip_min_length 1k;
    gzip_types text/plain application/javascript application/x-javascript text/css;

    server {
        listen       80;
        server_name  localhost;

        # 反向代理到Tomcat集群
        location / {
            proxy_pass http://tomcat_cluster;

            # 重要:传递客户端真实IP
            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_set_header X-Forwarded-Proto $scheme;

            # 连接超时设置
            proxy_connect_timeout 30s;
            proxy_read_timeout 120s;
            proxy_send_timeout 120s;

            # 启用长连接
            proxy_http_version 1.1;
            proxy_set_header Connection "";
        }

        # 静态文件处理(可选)
        location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 30d;
            proxy_pass http://tomcat_cluster;
        }

        # Nginx状态监控
        location /nginx_status {
            stub_status on;
            access_log off;
            allow 127.0.0.1;
            deny all;
        }
    }
}

4. 部署Web应用

创建测试应用 test-session.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head><title>Session Test</title></head>
<body>
    <h2>Tomcat集群会话测试</h2>
    <%
        String sessionId = session.getId();
        Integer counter = (Integer) session.getAttribute("counter");
        if (counter == null) {
            counter = 1;
        } else {
            counter++;
        }
        session.setAttribute("counter", counter);
    %>

    <p>服务器: <%= request.getLocalAddr() %>:<%= request.getLocalPort() %></p>
    <p>Session ID: <%= sessionId %></p>
    <p>访问次数: <%= counter %></p>
    <p>Session创建时间: <%= new java.util.Date(session.getCreationTime()) %></p>
</body>
</html>

将Web应用部署到两个Tomcat的 webapps/ROOT 目录。

四、启动和测试

1. 启动顺序

# 1. 启动Redis
C:\cluster\redis\redis-server.exe redis.windows.conf

# 2. 启动Tomcat集群
C:\cluster\tomcat1\bin\startup.bat
C:\cluster\tomcat2\bin\startup.bat

# 3. 启动Nginx
C:\cluster\nginx\nginx.exe
# 或
start nginx

2. 验证命令

# 检查进程
tasklist | findstr "nginx tomcat redis"

# 测试端口
netstat -ano | findstr :80
netstat -ano | findstr :8080
netstat -ano | findstr :8081
netstat -ano | findstr :6379

# 测试Redis连接
C:\cluster\redis\redis-cli.exe -h localhost -p 6379
> ping
> keys *

# 重新加载Nginx配置
nginx -s reload

# 停止Nginx
nginx -s quit

3. 访问测试

浏览器访问 http://localhost/test-session.jsp 多次刷新,观察:
  • 请求是否分配到不同Tomcat
  • Session计数器是否持续递增(证明会话共享成功)

五、进阶配置

1. Nginx健康检查

upstream tomcat_cluster {
    server localhost:8080;
    server localhost:8081;

    # 被动健康检查
    check interval=3000 rise=2 fall=3 timeout=1000 type=http;
    check_http_send "HEAD / HTTP/1.0\r\n\r\n";
    check_http_expect_alive http_2xx http_3xx;
}

2. 配置SSL(HTTPS)

server {
    listen 443 ssl;
    server_name yourdomain.com;

    ssl_certificate      cert.pem;
    ssl_certificate_key  cert.key;
    ssl_session_timeout  5m;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    location / {
        proxy_pass http://tomcat_cluster;
        # ... 其他配置
    }
}

3. Windows服务配置(开机自启)

创建启动脚本 start_cluster.bat

@echo off
title Web集群启动脚本

echo 启动Redis服务...
call net start RedisCluster 2>nul
if errorlevel 1 (
    echo Redis未安装为服务,直接启动...
    start "Redis" "C:\cluster\redis\redis-server.exe" "C:\cluster\redis\redis.windows.conf"
)

echo 启动Tomcat集群...
start "Tomcat1" "C:\cluster\tomcat1\bin\startup.bat"
timeout /t 5 /nobreak
start "Tomcat2" "C:\cluster\tomcat2\bin\startup.bat"

echo 启动Nginx...
cd /d "C:\cluster\nginx"
start nginx

echo 所有服务已启动!
echo 访问地址: http://localhost
pause

六、监控和维护

1. 监控脚本 monitor.bat

@echo off
echo === 集群状态监控 ===
echo.

echo [1] Nginx进程:
tasklist /fi "imagename eq nginx.exe"

echo.
echo [2] Tomcat进程:
tasklist /fi "imagename eq java.exe"

echo.
echo [3] Redis进程:
tasklist /fi "imagename eq redis-server.exe"

echo.
echo [4] 端口监听:
netstat -ano | findstr /c:":80 " /c:":8080" /c:":8081" /c:":6379"

echo.
echo [5] 访问测试:
curl -s http://localhost/test-session.jsp | findstr "服务器"
pause

2. 日志查看

# Nginx日志
tail -f C:\cluster\nginx\logs\access.log
tail -f C:\cluster\nginx\logs\error.log

# Tomcat日志
tail -f C:\cluster\tomcat1\logs\catalina.out
tail -f C:\cluster\tomcat2\logs\catalina.out

# Redis日志
type C:\cluster\redis\redis.log

七、故障排除

常见问题及解决方案:

端口冲突

netstat -ano | findstr :端口号
taskkill /F /PID 进程ID

Redis连接失败

  • 检查Redis是否启动
  • 检查防火墙设置
  • 验证密码配置

会话不共享

  • 检查tomcat-redis-session-manager的JAR版本
  • 确认context.xml配置正确
  • 查看Tomcat日志中的错误信息

Nginx 502错误

  • 检查Tomcat是否正常运行
  • 调整Nginx超时时间
  • 检查代理配置

这个方案可以实现高可用的Web集群,通过Redis实现了会话共享,Nginx提供了负载均衡和静态资源缓存,适合中小型项目的集群部署。