Saving Tomcat sessions
31 Jul 2018 | tags: Tomcat SpringRationale
Let’s supose you have a single Tomcat instance. So far so good, the Tomcat will keep the session in memory and everybody would be happy. But what if you want to keep those sessions after a Tomcat restart? Moreover, what if you want to have more than one Tomcat in a cluster?
### Persistence manager to the rescue
Tomcat ships with a module that allows you to persist the sessions either to disk or to a jdbc database. You can tweak that under $CATALINA_HOME/conf/context.xml.
Usage
Let’s suppose you want to save the sessions to a MySQL database. First, create a tomcat_sessions table with the following sql script:
create table tomcat_sessions (
session_id varchar(100) not null primary key,
valid_session char(1) not null,
max_inactive int not null,
lastaccess bigint not null,
app_context varchar(180),
session_data mediumblob,
KEY kapp_context(app_context)
);
Let’s suppose that table is in the test schema. Be careful with the lastaccess field, I guess there’s a bug somewhere, because the only way I managed to make it work was to use that field name.
Once we have it in place we can setup the Tomcat instance. Edit the context.xml file and add the following:
<Manager className="org.apache.catalina.session.PersistentManager"
maxIdleBackup="2"
maxIdleSwap="2"
minIdleSwap="1"
saveOnRestart="true">
<Store className="org.apache.catalina.session.JDBCStore"
connectionURL="jdbc:mysql://localhost/test?user=test&password=test& useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"
driverName="com.mysql.jdbc.Driver"
sessionIdCol="session_id"
sessionValidCol="valid_session"
sessionMaxInactiveCol="max_inactive"
sessionLastAccessCol="lastaccess"
sessionTable="tomcat_sessions"
sessionAppCol="app_context"
sessionDataCol="session_data"
/>
</Manager>
If there’s another Manager block, please remove it (or comment it out). Use your best judgment to select the right values for you (please refer to the Tomcat documentation at [1]). You will start to see the Tomcat sessions in that table.
[1] https://tomcat.apache.org/tomcat-9.0-doc/config/manager.html