前言
近期在学习一个新项目的时候,发现这个项目在手动重启之后,session里的数据仍然存在。查看了一下项目并没有做数据持久化和session缓存存储。而以前的项目给我的经验是项目重启,session就会被销毁清空.经过对项目的研究 学习到了一个新东西:spring-boot-devtools
介绍
spring-boot-devtools是一个Spring Boot官方提供的开发工具,它提供了很多有用的功能,例如自动重启、自动配置等,以提高开发效率。但是,spring-boot-devtools在重启应用程序时,不会清除Session数据,这是因为spring-boot-devtools使用了一个特殊的类加载器,它可以使得应用程序的类和资源可以在不重启JVM的情况下重新加载。
由于Session数据是保存在内存中的,而spring-boot-devtools的类加载器可以重载应用程序的类和资源,但是不能重载应用程序保存在内存中的Session数据,因此在应用程序重启后,Session数据仍然存在。
问题解决方案
如果您想要在应用程序重启时清除Session数据,可以使用如下方法:
- 手动清除Session数据
在应用程序重启时,可以编写一个ServletContextListener来清除Session数据。ServletContextListener是一个Servlet容器在启动和关闭时会通知的接口,可以通过实现这个接口并覆盖它的contextDestroyed方法来实现清除Session数据。例如:
public class SessionCleanupListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// do nothing
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// 清除Session数据
sce.getServletContext().setAttribute("sessionData", null);
}
}
然后,在web.xml中注册SessionCleanupListener:
<listener>
<listener-class>com.example.SessionCleanupListener</listener-class>
</listener>
-
使用持久化存储,将Session数据存储在外部存储介质中,例如数据库、缓存服务器等。这样,即使应用程序重启,Session数据也不会丢失。您可以使用如上文所述的方法之一来实现持久化存储。
-
使用Spring Session。Spring Session是一个用于管理Web应用程序中的Session数据的框架,它提供了多种Session存储后端,例如Redis、MongoDB、JDBC等。通过使用Spring Session,您可以将Session数据存储在外部存储介质中,并在应用程序重启时恢复Session数据。
-
使用一个ServletContextListener监听器,在ServletContext销毁时清除Session数据。在这种方法中,您需要编写一个实现ServletContextListener接口的类,并在contextDestroyed方法中清除Session数据。例如:
public class SessionCleanupListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// do nothing
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
HttpSession session = sce.getSession();
if (session != null) {
session.invalidate();
}
}
}
然后在web.xml中注册ServletContextListener:
<listener>
<listener-class>com.example.SessionCleanupListener</listener-class>
</listener>
这样,在应用程序重启时,ServletContextListener会被通知ServletContext销毁,从而清除Session数据。