Session的持久化

 

当一个 Session 开始时, Servlet 容器会为 Session 创建一个 HttpSession 对象。 Servlet 容器在某些情况下把这些 HttpSession 对象从内存中转移到文件系统或数据库中,在需要访问 HttpSession 信息时再把它们加载到内存中。

 

Session 的持久化是由 Session Manager 来管理的。 Tomcat 提供了两个实现类

l         org.apache.catalina.session.StandardManager

l         org.apache.catalina.session.PersistentManager

 

1.         StandardManager

Standard Manager 是默认的 Session Manager. 它的实现机制为:当 Tomcat 服务器关闭或重启,或者 web 应用被重新加载时,会对在内存中的 HttpSession 对象进行持久化,把它们保存到文件系统中,默认的文件为:

<CATALINA_HOME>/work/Catalina/hostname/applicationname/SESSIONS.ser

2.         PersistentManager

PersistentManager 能够把 Session 对象保存到 Session Stor 中,它提供了比 StandardManager 更为灵活的 Session 管理功能,它具有以下功能:

l         对内存中的 HttpSession 对象进行持久化,把它们保存到 Session Store

l         具有容错功能,及时把 Session 备份到 Session Store 中,当 Tomcat 服务器意外关闭后再重启时,可以从 Session Store 中恢复 Session 对象。

l         可以灵活控制在内存中的 Session 数目,将部分 Session 转移到 Session Store

Tomcat 实现持久化 Session Store 的接口为 org.apache.Catalina.store, 目前提供了两个实现这一接口的类: org.apache.Catalina.FileStore org.apache.Catalina.JDBCStore.

下面讨论如何配置 PersistentManager 以及两种持久化 Session Store.

 

配置 FileStore

 

FileStore HttpSession 对象保存在一个文件中。这个文件的默认目录为

<CATALINA_HOME>/work/Catalina/hostname/applicationname. 每个 HttpSession 对象都会对应一个文件,它以 Session ID 作为文件名,扩展名为: .session.

 

例:为 helloapp 应用配置 FileStore

Server.xml

<!-- configure FileStore -->

<Context path="/helloapp" docBase="helloapp" debug="0"

reloadable="true">

 

<Manager className="org.apache.catalina.session.PersistentManager" >

debug=0;

saveOnRestart="true"

maxActiveSessions="-1"

minIdleSwap="-1"

maxIdleSwap="-1"

maxIdleBackup="-1"

<Store className="org.apache.catalina.session.FileStore" directory="mydir" />

</Manager>

 

</Context>

 

 

配置 JDBCStore

 

JDBCStore HttpSession 对象保存在数据为库的一张表中。

 

例: MySQL 中创建 Session 表的步骤,假定表的名字为 tomcat_sessions, 这张表所在的数据库为 tomcatsessionDB.

 

CREATE DATABASE tomcatsessionDB;

Use tomcatsessionDB

Create table tomcat_session(

session_id  varchar(100) not null primary key,

valid_session chart(1)not null,

max_inactive int not null,

last_access bigint not null,

app_name varchar (255),

session_data mediumblob,

KEY kapp_name(app_name)

};

 

 

Server.xml

<!-- configure JDBCStore -->

<Context path="/helloapp" docBase="helloapp" debug="0"

reloadable="true">

 

<Manager className="org.apache.catalina.session.PersistentManager" >

debug=99;

saveOnRestart="true"

maxActiveSessions="-1"

minIdleSwap="-1"

maxIdleSwap="-1"

maxIdleBackup="-1"

<Store className="org.apache.catalina.session.JDBCStore"

driverName="com.mysql.jdbc.Driver"

connectionURL="jdbc:mysql://localhost/tomcatsessionDB?user=dbuser;password=1234"

sessionTable="tomcat_sessions"

sessionIdCol="session_id"

sessionDataCol="session_data"

sessionValidCol="valid_session"

sessionMaxInactiveCol="max_inactive"

sessionLastAccessedCol="last_access"

sessionAppCol="app_name"

checkInterval="60"

debug="99"

/>

</Manager>

 

</Context>

 

你可能感兴趣的:(Session的持久化)