I've tried using
public void onApplicationEvent(ApplicationEvent event)
{
if(event instanceof SessionDestroyedEvent){
and
@WebListener
public class SessionListener implements HttpSessionListener {
@Override
public void sessionDestroyed(HttpSessionEvent se) {
First one, I didn't get SessionDestoryedEvent
event at all.
It seems spring might notify us after session is expired.
Is there a reliable way to get notified before
session is expired?
Preferably I want solution without spring-session
package.
I'm not getting sessionDestroyed
nor sessionCreated
with the following code..
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.annotation.WebListener;
import org.springframework.stereotype.Component;
@WebListener
public class MySessionListener implements HttpSessionListener {
private static int totalActiveSessions;
public static int getTotalActiveSession(){
return totalActiveSessions;
}
public MySessionListener()
{
System.out.println("MySessionListener -------------");
}
@Override
public void sessionCreated(HttpSessionEvent arg0) {
totalActiveSessions++;
System.out.println("sessionCreated - add one session into counter");
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
totalActiveSessions--;
System.out.println("sessionDestroyed - deduct one session from counter");
}
}
Spring Session JDBC does not support publishing of session events due to the obvious limitations of an underlying data store in that regard. A relational database, by itself, has no pub-sub like mechanism that could be used to propagate events to all nodes in the cluster.
This is documented both in the reference manual and the JdbcOperationsSessionRepository
javadoc.
Regarding the second part of your question, with session stores that support event publishing (such as Redis and Hazelcast) Spring Session translates all the events it publishes to standard Servlet API's HttpSessionEvent
instances. While you could listen to Spring Session's event hierarchy is recommended to keep all session related interactions through standard Servlet API mechanisms.
Session events related to expiration/deletion are published when session is to be invalidated, as per HttpSession
and HttpSessionListener#sessionDestroyed
. I'm not sure what exactly do you mean by getting notified before session is expired, as it a vague term that depends on your expectations of how much before.