Tomcat - How to persist a session immediately to disk using PersistentManager + FileStore

codependent picture codependent · Mar 10, 2016 · Viewed 10.1k times · Source

I want to persist Tomcat's HttpSessions to disk so that it can be used in a scalable cloud environment. The point is that there will be a number of Tomcat nodes up (in a cloud PaaS) and clients can be directed to any of them. We want to persist and load the sessions from a shared disk unit.

I have configured the PersistentManager this way:

context.xml

<Manager className="org.apache.catalina.session.PersistentManager">
   <Store className="org.apache.catalina.session.FileStore" directory="c:/somedir"/>
</Manager>

The problem is that sessions are, apparently, never flushed to disk.

I changed the <Manager> config adding maxIdleBackup:

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

This way it takes almost a minute until I see the session persisted to disk. Oddly enough, the doc states that it should take around a second:

maxIdleBackup: The time interval (in seconds) since the last access to a session before it is eligible for being persisted to the session store, or -1 to disable this feature. By default, this feature is disabled.

Other config:

Following the documentation I set the system property

org.apache.catalina.session.StandardSession.ACTIVITY_CHECK -> true

Is there a way to immediately flush the session to disk? Is is possible to make that any change in the session is also persisted right away?

UPDATE:

I have tried to force the passivation of the session and flushing to disk with maxIdleBackup="0" minIdleSwap="0" maxIdleSwap="1", but it still takes almost a minute.

Answer

Arnaud Tournier picture Arnaud Tournier · Jun 2, 2016

You can also use this valve which is part of the Tomcat distribution (at least in version 8) :

<Valve className="org.apache.catalina.valves.PersistentValve"/>

This node has to be inserted before the <Manager className="org.apache.catalina.session.PersistentManager"> node in the context.xml file.

It will then use the store to maintain the session on each http request. Note that the documentation assumes that only one http request will be made by the same client at a time.

This will allow you to use non sticky session load balancer in front of your java ee servers.