在 CentOS 上搭建 Tomcat 集群的实用步骤
一、架构与准备
二、安装与基础配置
sudo yum install -y java-1.8.0-openjdk-develjava -version 与 javac -versionwget https://archive.apache.org/dist/tomcat/tomcat-9/v9.0.56/bin/apache-tomcat-9.0.56.tar.gz && tar xvf apache-tomcat-9.0.56.tar.gzsudo mv apache-tomcat-9.0.56 /opt/tomcat/node1/opt/tomcat/node1/bin/startup.shhttp://<节点IP>:8080 出现 Tomcat 欢迎页。三、配置 Tomcat 集群与会话复制
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
如需更可控的复制参数,可使用如下较完整示例(按需调整):<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="8">
<Manager className="org.apache.catalina.ha.session.DeltaManager"
expireSessionsOnShutdown="false"
notifyListenersOnReplication="true"/>
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Membership className="org.apache.catalina.tribes.membership.McastService"
address="228.0.0.4"
port="45564"
frequency="500"
dropTime="3000"/>
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
address="auto"
port="4000"
autoBind="100"
selectorTimeout="5000"
maxThreads="6"/>
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
</Sender>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor"/>
</Channel>
<Valve className="org.apache.cala.catalina.ha.tcp.ReplicationValve" filter=""/>
<Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
</Cluster>
关键要点:
<distributable/>
jvmRoute="tomcat1"、jvmRoute="tomcat2"。四、配置 Nginx 负载均衡
sudo yum install -y nginxhttp {
upstream tomcat_cluster {
server 192.168.1.11:8080;
server 192.168.1.12:8080;
# 可按需增加权重、健康检查等
}
server {
listen 80;
server_name yourdomain.com;
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;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
sudo systemctl start nginx && sudo systemctl enable nginxhttp://<Nginx_IP>/ 能正常打开应用,并在多节点间轮询。五、验证、扩展与常见问题