Spring Boot内嵌Tomcat session超时问题
最近让Spring Boot内嵌Tomcat的session超时问题给坑了一把。
在应用中需要设置session超时时间,然后就习惯的在application.properties配置文件中设置如下,
server.session.timeout=90
这里把超时时间设置的短些,主要想看看到底有没有起作用(不能设值30min然后再看吧,那样太不人道了)。结果没起作用,百度下发现Spring Boot 2后,配置变成如下,
server.servlet.session.timeout=90
但结果依然不起作用,后来就断断续续的懵了逼的找问题原因,各种百度,google,最后觉得还是看源代码吧,顺便也学习下。
1. 既然是Session超时时间问题,那就看看对Session的实现 - StandardSession
其中有isValid()方法
/**
* Return the <code>isValid</code> flag for this session.
*/
@Override
public boolean isValid() { if (!this.isValid) {
return false;
} if (this.expiring) {
return true;
} if (ACTIVITY_CHECK && accessCount.get() > 0) {
return true;
} if (maxInactiveInterval > 0) {
int timeIdle = (int) (getIdleTimeInternal() / 1000L);
if (timeIdle >= maxInactiveInterval) {
expire(true);
}
} return this.isValid;
}
看了下,这里的 timeIdle >= maxInactiveInterval就是触发session超时的判断,满足则调用 expire(true)。那么问题就来了,什么时候调用isValid()?
2. 后台肯定有定时调用isValid()的线程
查看调用isValid()的相关类如下,StandardManager和ManagerBase入了法眼了。

StandardManager中的注解表明是用来让所有存活的session过期的,应该是在web容器销毁时调用的,所以就只看 ManagerBase
// Expire all active sessions
Session sessions[] = findSessions();
for (int i = 0; i < sessions.length; i++) {
Session session = sessions[i];
try {
if (session.isValid()) {
session.expire();
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
} finally {
// Measure against memory leaking if references to the session
// object are kept in a shared field somewhere
session.recycle();
}
}
ManagerBase,注解表明是我们想要的,接下来看调用processExpires()的类。还是ManagerBase。
/**
* Invalidate all sessions that have expired.
*/
public void processExpires() { long timeNow = System.currentTimeMillis();
Session sessions[] = findSessions();
int expireHere = 0 ; if(log.isDebugEnabled())
log.debug("Start expire sessions " + getName() + " at " + timeNow + " sessioncount " + sessions.length);
for (int i = 0; i < sessions.length; i++) {
if (sessions[i]!=null && !sessions[i].isValid()) {
expireHere++;
}
}
long timeEnd = System.currentTimeMillis();
if(log.isDebugEnabled())
log.debug("End expire sessions " + getName() + " processingTime " + (timeEnd - timeNow) + " expired sessions: " + expireHere);
processingTime += ( timeEnd - timeNow ); }
调用processExpires()
/**
* Frequency of the session expiration, and related manager operations.
* Manager operations will be done once for the specified amount of
* backgroundProcess calls (ie, the lower the amount, the most often the
* checks will occur).
*/
protected int processExpiresFrequency = 6;
/**
* {@inheritDoc}
* <p>
* Direct call to {@link #processExpires()}
*/
@Override
public void backgroundProcess() {
count = (count + 1) % processExpiresFrequency;
if (count == 0)
processExpires();
}
看到backgroundProcess()方法名就知道离真理不远了。其调用如下,在StandardContext类中,
@Override
public void backgroundProcess() { if (!getState().isAvailable())
return; Loader loader = getLoader();
if (loader != null) {
try {
loader.backgroundProcess();
} catch (Exception e) {
log.warn(sm.getString(
"standardContext.backgroundProcess.loader", loader), e);
}
}
Manager manager = getManager();
if (manager != null) {
try {
manager.backgroundProcess();
} catch (Exception e) {
log.warn(sm.getString(
"standardContext.backgroundProcess.manager", manager),
e);
}
}
WebResourceRoot resources = getResources();
if (resources != null) {
try {
resources.backgroundProcess();
} catch (Exception e) {
log.warn(sm.getString(
"standardContext.backgroundProcess.resources",
resources), e);
}
}
InstanceManager instanceManager = getInstanceManager();
if (instanceManager instanceof DefaultInstanceManager) {
try {
((DefaultInstanceManager)instanceManager).backgroundProcess();
} catch (Exception e) {
log.warn(sm.getString(
"standardContext.backgroundProcess.instanceManager",
resources), e);
}
}
super.backgroundProcess();
}
但是还没有看到线程的创建,继续查看调用,ContainerBase.ContainerBackgroundProcessor
/**
* Private thread class to invoke the backgroundProcess method
* of this container and its children after a fixed delay.
*/
protected class ContainerBackgroundProcessor implements Runnable
while (!threadDone) {
try {
Thread.sleep(backgroundProcessorDelay * 1000L);
} catch (InterruptedException e) {
// Ignore
}
if (!threadDone) {
processChildren(ContainerBase.this);
}
}
看到曙光了!看来后台线程每隔 backgroundProcessorDelay * processExpiresFrequency (s)来判断session是否过期。
默认值:
backgroundProcessorDelay = 30s
ServerProperties.class
/**
* Delay between the invocation of backgroundProcess methods. If a duration suffix
* is not specified, seconds will be used.
*/
@DurationUnit(ChronoUnit.SECONDS)
private Duration backgroundProcessorDelay = Duration.ofSeconds(30);
processExpiresFrequency = 6
所以默认情况下后台线程每隔3min去判断session是否超时。这样我之前设置server.servlet.session.timeout=90s,没办法看到效果的。
另外还要注意后台对timeout的处理以min为单位,即90s在后台会认为是1min的。
TomcatServletWebServerFactory.class
private long getSessionTimeoutInMinutes() {
Duration sessionTimeout = getSession().getTimeout();
if (isZeroOrLess(sessionTimeout)) {
return 0;
}
return Math.max(sessionTimeout.toMinutes(), 1);
}
Spring Boot内嵌Tomcat session超时问题的更多相关文章
- Spring Boot 内嵌Tomcat的端口号的修改
操作非常的简单,不过如果从来没有操作过,也是需要查找一下资料的,所以,在此我简单的记录一下自己的操作步骤以备后用! 1:我的Eclipse版本,不同的开发工具可能有所差异,不过大同小异 2:如何进入对 ...
- 如何优雅的关闭基于Spring Boot 内嵌 Tomcat 的 Web 应用
背景 最近在搞云化项目的启动脚本,觉得以往kill方式关闭服务项目太粗暴了,这种kill关闭应用的方式会让当前应用将所有处理中的请求丢弃,响应失败.这种形式的响应失败在处理重要业务逻辑中是要极力避免的 ...
- Spring Boot启动过程(四):Spring Boot内嵌Tomcat启动
之前在Spring Boot启动过程(二)提到过createEmbeddedServletContainer创建了内嵌的Servlet容器,我用的是默认的Tomcat. private void cr ...
- Spring Boot 内嵌容器 Tomcat / Undertow / Jetty 优雅停机实现
Spring Boot 内嵌容器 Tomcat / Undertow / Jetty 优雅停机实现 Anoyi 精讲JAVA 精讲JAVA 微信号 toooooooozi 功能介绍 讲解java深层次 ...
- Spring Boot 容器选择 Undertow 而不是 Tomcat Spring Boot 内嵌容器Unde
Spring Boot 内嵌容器Undertow参数设置 配置项: # 设置IO线程数, 它主要执行非阻塞的任务,它们会负责多个连接, 默认设置每个CPU核心一个线程 # 不要设置过大,如果过大,启动 ...
- Spring boot 内置tomcat禁止不安全HTTP方法
Spring boot 内置tomcat禁止不安全HTTP方法 在tomcat的web.xml中可以配置如下内容,让tomcat禁止不安全的HTTP方法 <security-constraint ...
- Spring Boot内置Tomcat
Spring Boot默认支持Tomcat/Jetty/Undertow作为底层容器.在之前实战相关的文章中,可以看到引入spring-boot-starter-web就默认使用tomcat容器,这是 ...
- SpringBoot Boot内嵌Tomcat
Spring Boot: SpringBoot-start-web 里面依赖的环境中 如果是外部的Tomcat 容器,可以通过修改config进行配置 内嵌的呢? 如何定制和修改Servlet容器的相 ...
- 自定义Spring Boot内置tomcat的404页面
spring boot 的相关404页面配置都是针对项目路径下的(如果配置了 context-path) 在context-path不为空的情况下,如果访问路径不带context-path,这时候会显 ...
随机推荐
- vue插槽slot的理解与使用
一.个人理解及插槽的使用场景 刚开始看教程我的疑惑是为什么要用插槽,它的使用场景是什么,很多解释都是“父组件向子组件传递dom时会用到插槽”,这并不能很好的解决我的疑惑.既然你用了子组件,你为什么要给 ...
- Wannafly挑战赛22 A-计数器(gcd,裴蜀定理)
原题地址 题目描述 有一个计数器,计数器的初始值为0,每次操作你可以把计数器的值加上a1,a2,...,an中的任意一个整数,操作次数不限(可以为0次),问计数器的值对m取模后有几种可能. 输入描述: ...
- Web/JAVA 简单题目汇总
[Java标识符,变量.常量] 一.Java合法标识符命名规则 (1)区分字母大小写,标识符长度不限 (2) 英文,Unicode码双字节文字字符(日文,韩文,中文),数字,下划线,$(美元符号)均 ...
- POJ 3368 Frequent values(线段树区间合并)
[题目链接] http://poj.org/problem?id=3368 [题目大意] 有一个有序序列,要求区间查询出现次数最多的数 [题解] 维护每个区间左端点和右端点,以及左右的长度,还有区间的 ...
- python3 全栈开发 -- 面向对象 类的组合和封装
一.类的组合 1.什么是组合 组合:描述的是类与类之间的关系,是一种什么有什么关系 一个类产生的对象,该对象拥有一个属性,这个属性的值是来自于另外一个类的对象 2.什么是继承(回顾一下) 继承:描述的 ...
- C# 事件和Unity3D
http://zijan.iteye.com/blog/871207 翻译自: http://www.everyday3d.com/blog/index.php/2010/10/04/c-events ...
- HashMap在高并发下引起的死循环
HashMap事实上并非线程安全的,在高并发的情况下,是非常可能发生死循环的,由此造成CPU 100%,这是非常可怕的.所以在多线程的情况下,用HashMap是非常不妥当的行为,应採用线程安全类Con ...
- mapx 32位在win8 64位上使用
在可以安装32位mapx的电脑上安装并破解后,将安装文件复制出来,放到c盘根目录下,用下面语句进行注册即可 Regsvr32 C:\MapX\Mapx50.DLL Regsvr32 C:\\MapX\ ...
- vs2010 sharepoint项目部署与查看
1.选中sharepoint项目,视图→属性窗口,填写站点url ,我这里原来写81,但是81已经放了另外一个项目,所以要把它改为刚刚新增的82端口 不知道影不影响,反正我重新打开了一遍. 2.重新生 ...
- Shell--变量内容的删除、替代与替换
1. 变量内容的删除与替换 #代表由前面开始删除,所以这里便由开始的/删起,*来代替0到无穷多个任意字符 %由后面向前删除变量内容 例如:echo ${path%:*bin}删除最有一个目录,即从:到 ...