Java Spring启动会话超时事件侦听器

Java Spring启动会话超时事件侦听器,java,spring,session,events,timeout,Java,Spring,Session,Events,Timeout,我想在用户从会话超时注销时执行自定义事件。用户完全在my application指定的时间长度后成功注销。属性: server.servlet.session.timeout=10 server.servlet.session.cookie.max-age=10 我发现了一些类似的解决方案,涉及SessionDestroyeEvent,例如: @Slf4j @Component public class SessionExpiredListener implements Application

我想在用户从会话超时注销时执行自定义事件。用户完全在my application指定的时间长度后成功注销。属性:

server.servlet.session.timeout=10
server.servlet.session.cookie.max-age=10
我发现了一些类似的解决方案,涉及SessionDestroyeEvent,例如:

@Slf4j
@Component
public class SessionExpiredListener implements ApplicationListener<SessionDestroyedEvent> {

    @Override
    public void onApplicationEvent(SessionDestroyedEvent event) {
        for (SecurityContext securityContext : event.getSecurityContexts()) {
            Authentication authentication = securityContext.getAuthentication();
            UserPrincipal user = (UserPrincipal) authentication.getPrincipal(); // UserPrincipal is my custom Principal class
            log.debug("Session expired!" + user.getUsername());
            // do custom event handling
        }
    }
}
@Slf4j
@组成部分
公共类SessionExpiredListener实现ApplicationListener{
@凌驾
Application event(SessionDestroyeEvent事件)上的公共无效{
对于(SecurityContext SecurityContext:event.getSecurityContext()){
Authentication=securityContext.getAuthentication();
UserPrincipal用户=(UserPrincipal)身份验证。getPrincipal();//UserPrincipal是我的自定义主体类
log.debug(“会话已过期!”+user.getUsername());
//执行自定义事件处理
}
}
}
问题是SessionDestroyeEvent不会在会话超时的同时触发,在我的测试中,它会在会话过期后5分钟内触发

我还尝试在HttpSessionListener中使用sessionDestroyed,但结果类似

是否有一个事件会在会话到期时触发,或者是否有某种方法可以实现此目的?

当web容器使会话到期时,将调用
sessionDestroyed()
方法。 在Tomcat中,会话过期每分钟都会发生,我认为其他servlet容器也是如此。 因此,即使在会话超时之后,也可能会有延迟,直到下一次检测到过期

会话管理是由servlet容器完成的,您的应用程序将从中获得通知。
而且无法在会话到期的确切时间得到通知。

我还处理了用户在会话超时时注销的事件。对我来说,这个解决方案很有帮助:


此外,我还必须注册中提到的HttpSessionEventPublisher,因为我没有用于侦听器注册的web.xml。

感谢您的及时回复。所以基本上没有办法。遗憾的是,我有一个登录用户列表,我想在会话超时时更新这些用户,我也许可以使用SessionRegistry实现同样的功能,并让Spring在内部处理。很高兴知道我不应该一直浪费时间寻找一个不存在的解决方案!