Spring Session Redis最佳实践(4)Session监听器

    xiaoxiao2023-11-22  30

    欢迎转至站内查看原文,链接为:https://www.chendd.cn/information/viewInformation/experienceShare/312.a

    在说前文中的Spring Session JDBC的时候,废了很大的劲儿和时间最终得出来的是JDBC的方式不能实现Session监听功能,后来也琢磨明白了,我们面向数据库存储的方式可以非常轻易的去实现session类监听的功能,而Redis的实现也发现只支持HttpSessionListener类型事件,至于web容器中HttpSessionBindingListener与HttpSessionAttributeListener等事件不支持(截至目前我是这么认为的)。其实在RedisHttpSessionConfiguration的源码里面可以看到所支持的所有httpSessionListeners事件类型,通过增加session监听器的实现类即可。

    (1)xml配置文件如下(设置session超时事件为60秒)

    <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">     <property name="defaultRedisSerializer" ref="fastJsonRedisSerializer" />     <property name="maxInactiveIntervalInSeconds" value="60" />     <property name="httpSessionListeners">         <list>             <bean class="cn.chendd.session.listeners.RedisSessionListener" />         </list>     </property> </bean>

    (2)RedisSessionListener.java定义

    package cn.chendd.session.listeners; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /**  * session监听器  */ public class RedisSessionListener implements HttpSessionListener {     @Override     public void sessionCreated(HttpSessionEvent event) {         System.out.println("sessionCreated-->" + event.getSession().getId());     }     @Override     public void sessionDestroyed(HttpSessionEvent event) {         System.out.println("sessionDestroyed-->" + event.getSession().getId());     } }

    (3)运行效果截图

    其它说明

    (1)Spring Session是无缝集成的HttpSession,所以以前的session怎么使用,现在也一样;

    (2)上面的几种web监听器无法再使用web.xml中原始的配置方式了,因为现在的session不是原始的HttpSession,包括session的超时时间;

    源码下载

    https://gitee.com/88911006/chendd-examples

    最新回复(0)