如何在Sping Boot /Spring Webflux中设置会话超时

i2byvkas  于 2023-04-06  发布在  Spring
关注(0)|答案(2)|浏览(295)

我使用的是Sping Boot 2.7.0,我已经设置了
server.reactive.session.timeout=10s
在我的application.properties中。我使用@EnableWebFlux注解,但EnableWebFluxConfiguration类中的代码从未运行过(使用调试器进行了验证,并且我的会话在10秒后不会超时)。在TRACE日志中,我看到

TRACE 279856 --- [           main] o.s.b.a.condition.OnBeanCondition        : Condition OnBeanCondition on org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration did not match due to @ConditionalOnMissingBean (types: org.springframework.web.reactive.config.WebFluxConfigurationSupport; SearchStrategy: all) found beans of type 'org.springframework.web.reactive.config.WebFluxConfigurationSupport' org.springframework.web.reactive.config.DelegatingWebFluxConfiguration

这是未创建的bean

@Bean
        @ConditionalOnMissingBean(name = WebHttpHandlerBuilder.WEB_SESSION_MANAGER_BEAN_NAME)
        public WebSessionManager webSessionManager(ObjectProvider<WebSessionIdResolver> webSessionIdResolver) {
            DefaultWebSessionManager webSessionManager = new DefaultWebSessionManager();
            Duration timeout = this.serverProperties.getReactive().getSession().getTimeout();
            webSessionManager.setSessionStore(new MaxIdleTimeInMemoryWebSessionStore(timeout));
            webSessionIdResolver.ifAvailable(webSessionManager::setSessionIdResolver);
            return webSessionManager;
        }
unhi4e5o

unhi4e5o1#

我把MaxIdleTimeInMemoryWebSessionStore的定义复制到我自己的config类中,并硬编码会话超时,而不是从属性文件中阅读。

@SpringBootApplication
@EnableWebFlux
public class MyApplication {    
    
    static final class MaxIdleTimeInMemoryWebSessionStore extends InMemoryWebSessionStore {

        private final Duration timeout;

        private MaxIdleTimeInMemoryWebSessionStore(Duration timeout) {
            this.timeout = timeout;
        }

        @Override
        public Mono<WebSession> createWebSession() {
            return super.createWebSession().doOnSuccess(this::setMaxIdleTime);
        }

        private void setMaxIdleTime(WebSession session) {
            session.setMaxIdleTime(this.timeout);
        }
    }
        
    @Bean
    public WebSessionManager webSessionManager(@Autowired WebSessionIdResolver webSessionIdResolver) {
        DefaultWebSessionManager webSessionManager = new DefaultWebSessionManager();
        Duration timeout = Duration.ofSeconds(10);
        webSessionManager.setSessionStore(new MaxIdleTimeInMemoryWebSessionStore(timeout));
        webSessionManager.setSessionIdResolver(webSessionIdResolver);
        return webSessionManager;
    }
dzhpxtsq

dzhpxtsq2#

在application.yml中你可以调整它,这里我把它设置为36000秒。

server:
  reactive:
    session:
      timeout: 36000s

相关问题