实验环境:
两台服务器,分别实现java
其中一台作为nginx代理
实验原理图:
一、实现java环境
1、实现java的运行环境
(1)安装 JDK
可以在网上下载包
yum localinstall jdk-8u144-linux-x64.rpm
2、下载tomcat包解压
tar xvf apache-tomcat-8.5.11.tar.gz
mv apache-tomcat-7.0.78 /usr/local/tomcat
3、创建环境配置脚本
vim /etc/profile.d/java.sh
export JAVA_HOME=/usr/java/jdk1.8.0_144
export JRE_HOME=$JAVA_HOME/jre
export CATALINA_BASE=/usr/local/tomcat
export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$CATALINA_BASE/bin:$PATH
4、变量生效
source /etc/profile.d/java.sh
二、配置nginx代理后端服务器
yum insatll nginx -y
vim /etc/nginx/nginx.conf
在http端添加
upstream realserver {
server 172.17.25.132:8080 weight=2;
server 172.17.25.131:8080 weight=1;
}
server {
listen 80;
server_name localhost;
root /usr/local/tomcat/webapps;
location / {
index index.jsp;
proxy_pass http://realserver;
}
...
}
三、在两台服务器上配置tomcat
1、 vim /usr/local/tomcat/conf/server.xml
写在<Engine ...>中
<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.MessageDispatch15Interceptor"/>
</Channel>
<Valve className="org.apache.catalina.ha.tcp.ReplicationValve" filter="/"/>
<Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
</Cluster>
2、建立测试页面
mkdir /usr/local/tomcat/webapps/test
cd /usr/local/tomcat/webapps/test
vim index.jsp
注意:一台服务器title,h1写出TomcatA,一台写出TomcatB
<%@ page language="java" %>
<html>
<head><title>TomcatB</title></head>
<body>
<h1><font color="blue">TomcatB </h1>
<table align="centre" border="1">
<tr>
<td>Session ID</td>
<% session.setAttribute("abc","abc"); %>
<td><%= session.getId() %></td>
</tr>
<tr>
<td>Created on</td>
<td><%= session.getCreationTime() %></td>
</tr>
</table>
</body>
</html>
3、保持session会话
vim /usr/local/tomcat/conf/web.xml
在倒数第二行添加
<distributable/>
4、cd /usr/local/tomcat/webapps/test
mkdir WEB-INF
cd WEB-INF
cp /usr/local/tomcat/conf/web.xml .
catalina.sh start 启动服务
ss -ntl 查看8080端口是否打开
ps aux|grep tomcat
四、测试
在浏览器上测试
http://172.17.25.131/test/index.jsp
可以看到只有标题变化,但是session是不变的。