使用ServletContextListener关闭Redisson连接

  •  ServletContextListener 监听器

在 Servlet API 中有一个 ServletContextListener 接口,它能够监听 ServletContext 对象的生命周期,实际上就是监听 Web 应用的生命周期。

当Servlet 容器启动或终止Web 应用时,会触发ServletContextEvent 事件,该事件由ServletContextListener 来处理。在 ServletContextListener 接口中定义了处理ServletContextEvent 事件的两个方法。

   /**
     * 当Servlet 容器启动Web 应用时调用该方法。在调用完该方法之后,容器再对Filter 初始化,
     * 并且对那些在Web 应用启动时就需要被初始化的Servlet 进行初始化。
     */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

    }


    /**
     * 当Servlet 容器终止Web 应用时调用该方法。在调用该方法之前,容器会先销毁所有的Servlet 和Filter 过滤器。
     */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        // 关闭Reddson的线程池连接
        RedisUtils.shutdown();
    }
  • 监听器介绍

在JavaWeb被监听的事件源为:ServletContext、HttpSession、ServletRequest,即三大域对象。

总共八个监听器,监听域对象相关的操作

监听器的对象和方法的调用都是由服务器自己调用,不能手动参与。

域对象相关监听器
ServletContextListener:Tomcat启动和关闭时调用下面两个方法

public void contextInitialized(ServletContextEvent evt):ServletContext对象被创建后调用;
public void contextDestroyed(ServletContextEvent evt):ServletContext对象被销毁前调用;
HttpSessionListener:开始会话和结束会话时调用下面两个方法

public void sessionCreated(HttpSessionEvent evt):HttpSession对象被创建后调用;
public void sessionDestroyed(HttpSessionEvent evt):HttpSession对象被销毁前调用;
ServletRequestListener:开始请求和结束请求时调用下面两个方法

public void requestInitiallized(ServletRequestEvent evt):ServletRequest对象被创建后调用;
public void requestDestroyed(ServletRequestEvent evt):ServletRequest对象被销毁前调用。

域属性相关监听器

ServletContextAttributeListener:在ServletContext域进行增、删、改属性时调用下面方法。

扫描二维码关注公众号,回复: 5357863 查看本文章

public void attributeAdded(ServletContextAttributeEvent evt)
public void attributeRemoved(ServletContextAttributeEvent evt)
public void attributeReplaced(ServletContextAttributeEvent evt)
HttpSessionAttributeListener:在HttpSession域进行增、删、改属性时调用下面方法

public void attributeAdded(HttpSessionBindingEvent evt)
public void attributeRemoved (HttpSessionBindingEvent evt)
public void attributeReplaced (HttpSessionBindingEvent evt)
ServletRequestAttributeListener:在ServletRequest域进行增、删、改属性时调用下面方法

public void attributeAdded(ServletRequestAttributeEvent evt)
public void attributeRemoved (ServletRequestAttributeEvent evt)
public void attributeReplaced (ServletRequestAttributeEvent evt)

猜你喜欢

转载自www.cnblogs.com/yuhuashang-edward/p/10451491.html