1、把以下jar放进tomcat的lib目录
commons-pool2-2.2.jar
jedis-2.5.2.jar
tomcat-redis-session-manage-tomcat7.jar
2、编辑conf目录的context.xml,加入以下内容
<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve"/>
<Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
host="192.168.30.61"
port="6379"
database="0"
password="abc123456"
maxInactiveInterval="60" />
3、要持久化的bean必须 implements Serializable
要持久化的对象(session.setAttribute()里的对象)必须实现序列化(implements Serializable), 否则启动的时候会报NotSerializableException的异常.
下面来验证两个tomcat都是使用redis存取session
- 配置两个tomcat分别为
apache-tomcat-test1
apache-tomcat-test2
- 配置apache-tomcat-test1的server.xml
<Connector port="8081"
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8445" URIEncoding="utf-8"/>
<Connector port="8010" protocol="AJP/1.3" redirectPort="8445" URIEncoding="utf-8"/>
- 配置apache-tomcat-test2的server.xml
<Server port="8007" shutdown="SHUTDOWN">
<Connector port="8082" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8446" URIEncoding="utf-8"/>
<Connector port="8011" protocol="AJP/1.3" redirectPort="8446" URIEncoding="utf-8"/>
编写访问页面
- 在两个tomcat都新建一个项目redisSession
- 在redisSession目录新建一个测试页面index.jsp
- 编写tomcat1的index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML><html lang="en"><head>
<meta charset="UTF-8">
<title>Apache Tomcat Examples_1</title>
</head>
<body>
<p>
<h3>Apache Tomcat Examples-redis-server-1</H3>
<%=request.getParameter("name")%>
<%
String name = request.getParameter("name");
if (name != null && !name.equals("")) {
request.getSession().setAttribute("name", name);
System.out.println("Apache Tomcat Examples-redis-server-1");
}
%>
<p>
<%=request.getSession().getAttribute("name")%>
</p>
</body>
</html>
- 编写tomcat2的index.jsp的内容
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML><html lang="en"><head>
<meta charset="UTF-8">
<title>Apache Tomcat Examples_2</title>
</head>
<body>
<p>
<h3>Apache Tomcat Examples-redis-server-<font color='red'>2</font></H3>
<p>
<% System.out.println("Apache Tomcat Examples-redis-server-2");%>
</p>
<p>
<%=request.getSession().getAttribute("name")%>
</p>
</body>
</html>
启动两个 tomcat
- 先访问tomcat1
http://localhost:8081/redisSession/index.jsp?name=yiliang
- 再访问tomcat2
http://localhost:8082/redisSession/index.jsp
由于tomcat2是没有设置session的,但request.getSession().getAttribute(“name”)还是有值
证实了两个tomcat确实用redis存取session.