【问题标题】:Is there a way to have a function run when a session is created or expired?有没有办法在会话创建或过期时运行函数?
【发布时间】:2019-04-14 01:10:45
【问题描述】:

我目前正在计划一个应用程序,该应用程序需要一个函数来在会话创建和到期时运行。我计划使用类似 redis 的东西,但我对其他想法持开放态度。我正在寻找的是一个 n 注释,例如 @whenexpires 和 @whencreated。我知道会话的大部分注释都在课堂上,而不是方法谢谢。

【问题讨论】:

    标签: spring-boot spring-mvc spring-session


    【解决方案1】:

    从 Servlet 规范 2.3 开始,Apache Tomcat 等 Java Servlet 容器提供了HttpSessionListener 接口,以便在创建或销毁会话时执行自定义逻辑。基本用法:

    package com.example;
    
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    
    public class MySessionListener implements HttpSessionListener {
    
      @Override
      public void sessionCreated(HttpSessionEvent event) {
      }
    
      @Override
      public void sessionDestroyed(HttpSessionEvent event) {
      }
    }
    

    MySessionListener 添加到您的web.xml 中,或者——如果是Spring——为它声明一个Spring 检测到的Spring bean。但是,不需要 Spring,因为 HttpSessionListener 是 Java Servlet 规范的一部分。

    如果您使用 Redis 进行 Spring Session,您可以继续使用您的 HttpSessionListener,方法是将其添加到 Spring 配置中,如 official docs 中所述。

    @EnableRedisHttpSession 
    public class Config {
    
        @Bean
        public MySessionListener mySessionListener() {
            return new MySessionListener(); 
        }
    
        // more Redis configuration comes here...
    }
    

    此外,Spring Session 还支持“Spring-native”事件订阅和发布方式:ApplicationEvent。根据会话持久性方法,目前您的应用程序最多可以捕获三个事件:SessionExpiredEventSessionCreatedEventSessionDestroyedEvent

    实现EventListener 以便订阅 Spring Session 事件,例如:

    package com.example;
    
    import org.springframework.context.event.EventListener;
    import org.springframework.session.events.SessionCreatedEvent;
    import org.springframework.session.events.SessionDestroyedEvent;
    import org.springframework.session.events.SessionExpiredEvent;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MySessionEventListener {
    
        @EventListener
        public void sessionDestroyed(SessionDestroyedEvent event) {
        }
    
        @EventListener
        public void sessionCreated(SessionCreatedEvent event) {
        }
    
        @EventListener
        public void sessionExired(SessionExpiredEvent event) {
        }
    }
    

    【讨论】:

    • 我应该使用组件、配置还是bean注解?
    • @NicholasBegg 在 Spring 中,@Component 注释表示一个应该是 Spring 管理的组件的类。 @Component 是最通用的刻板印象,而 @ConfigurationRepository 或其他是专业化的。所有的目的是 Spring 能够通过扫描类路径来自动检测这些类。 EventListeners 或HttpSessionListeners 的实现应该用@Component 表示。但是,在 Spring 应用程序中有一些用例,其中配置类适合显式定义 bean。那些 bean 初始化方法需要@Bean
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 2012-04-20
    • 2011-11-07
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多