springboot内嵌tomcat的临时目录问题

1. 背景

线上保障,上线运行了几天的SpringBoot应用,突然遇到问题:/tmp/tomcatXXX/work/Tomcat/localhost/XXX is not valid。

2. 分析

应用不会存在/tmp/tomcatXXX/work/Tomcat/localhost/ROOT目录。经查询,是tomcat在文件上传时,会先对文件进行复制到临时目录,就是该目录。之前的应用运行是正常的,现在出现这个情况,显然是创建好的目录被删除了。对,就是这个特殊的/tmp目录Linux存在清除策略。

清除策略的配置文件路径如下:

/usr/lib/tmpfiles.d/tmp.conf

打开

#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

# See tmpfiles.d(5) for details

# Clear tmp directories separately, to make them easier to override
v /tmp 1777 root root 10d          
v /var/tmp 1777 root root 30d      

# Exclude namespace mountpoints created with PrivateTmp=yes
x /tmp/systemd-private-%b-*
X /tmp/systemd-private-%b-*/tmp
x /var/tmp/systemd-private-%b-*
X /var/tmp/systemd-private-%b-*/tmp

发现会清除10天内没被访问过的文件。但是到了这里,有个疑问就是,昨天可以的也就是该目录是被访问过,今天怎么会被清除咧?

这个本人确实当时很疑惑,然后对应用的假设为:/tmp/tomcat.4344543554352.8080/work/Tomcat/localhost/test,发现该目录下为空。也就是临时文件会被tomcat清理掉,但是test目录的创建时间确实是在10天前。

    到了这里就明白了,虽然test目录下文件每天都会有更新,但是**不会影响test目录的访问时间**,并且该文件被删掉了。/tmp目录的清理机制发现test空目录是10天前,就直接清理了(**test为空目录**)。应用再去访问就报错了。

3. 方案

原因搞清楚了,解决方案自然很明了,大致有3种:

  • 从Linux层面修改 /tmp目录的清理策略

    比较简单,略过

  • 修改tomcat的临时目录

    application.yml配置server.tomcat.basedir,修改tomcat临时目录的位置,也比较简单。

  • tomcat在临时目录不存在先创建

    这个方案稍微麻烦些,就多啰嗦下。其实该方式在spring-boot2.1.4版本进行了修订:在临时目录不存在就创建临时目录。
    

在该类spring-boot/src/main/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactory.java中添加了几行代码:

        catch (NoSuchMethodError ex) {
            // Tomcat is < 8.0.30. Continue
        }
        //新增代码开始
        try {
            context.setCreateUploadTargets(true);
        }
        catch (NoSuchMethodError ex) {
            // Tomcat is < 8.5.39. Continue.
        }
         //新增代码结束
         SkipPatternJarScanner.apply(context, this.tldSkipPatterns);

详情请看讨论:
https://github.com/spring-projects/spring-boot/issues/5009

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容