Spring Session Redis best practice (4) Session listener

Welcome to the site to view the original text, the link is: https://www.chendd.cn/information/viewInformation/experienceShare/312.a

When talking about Spring Session JDBC in the previous article, after a lot of effort and time wasted, it was finally concluded that the JDBC method cannot implement the Session monitoring function. Later, I figured it out, and our database-oriented storage method can be very easy. To realize the function of session class monitoring, and the implementation of Redis also found that only HttpSessionListener type events are supported. As for the events such as HttpSessionBindingListener and HttpSessionAttributeListener in the web container, they do not support (as of now, I think so). In fact, in the source code of RedisHttpSessionConfiguration, you can see all supported httpSessionListeners event types, just by adding the implementation class of the session listener.

(1) The xml configuration file is as follows (set the session timeout event to 60 seconds)

<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 definition

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) Screenshot of running effect

blob.png

other instructions

(1) Spring Session is a seamlessly integrated HttpSession, so how to use the previous session is the same now;

(2) The above web listeners can no longer use the original configuration method in web.xml, because the current session is not the original HttpSession, including the session timeout;

Source code download

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

Guess you like

Origin blog.csdn.net/haiyangyiba/article/details/90552326