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

欢迎转至站内查看原文,链接为: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)运行效果截图

blob.png

其它说明

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

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

源码下载

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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值