SpringBoot 默认使用的是 Servlet 容器的 Session 实现方式,可以通过配置来设置 Session 的过期时间。

在 application.properties 中添加以下配置:

# Session 过期时间,单位为秒
server.servlet.session.timeout=1800

这样就可以将 Session 的过期时间设置为 30 分钟。需要注意的是,如果有请求过来,Session 的过期时间会重新计算。如果希望无论是否有请求过来,都在 30 分钟后过期,可以使用以下方式:

@Configuration
public class SessionConfig {

    @Bean
    public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
        return new ServletListenerRegistrationBean<>(new HttpSessionEventPublisher());
    }

    @Bean
    public HttpSessionListener httpSessionListener() {
        return new HttpSessionListener() {
            @Override
            public void sessionCreated(HttpSessionEvent se) {
                se.getSession().setMaxInactiveInterval(1800);
            }

            @Override
            public void sessionDestroyed(HttpSessionEvent se) {

            }
        };
    }
}

这样就可以将 Session 的过期时间固定为 30 分钟,无论是否有请求过来。

SpringBoot 如何设置不论是否存在请求30分钟后都进行session过期

原文地址: https://www.cveoy.top/t/topic/bAwo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录