springboot内嵌tomcat临时目录问题
听说后面上线可能tomcat临时文件夹会被linux删除,会报找不到错误,现在赶紧记录一下,已被不时之需。
存在文件上传的springboot项目,在linux系统部署之后,会在系统的tmp目录下生成一个带tomcat 及 随机字符串的临时目录。
该目录有可能被linux系统在一定时间后自动清除掉,导致再次上传文件的时候,系统就会报错。
意思是tomcat的临时目录会被tmpwatch
删除掉,甚至可能删除掉class
文件,导致错误的发生
1.背景
线上保障,上线运行了几天的springboot应用,突然遇到问题:
/tmp/tomcatxxx/work/tomcat/localhost/xxx is not valid。
应用不会存在/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为空目录**)。应用再去访问就报错了。
2.方案
原因搞清楚了,解决方案自然很明了,大致有3种:
- 1.从linux层面修改 /tmp目录的清理策略,比较简单,略过
- 2.指定新的系统临时文件路径
-djava.io.tmpdir=/var/tmp
- 3. 配置中修改tomcat的临时目录
server: tomcat: basedir: /var/tmp/
3.代码中配置tomcat临时目录
@configuration public class multipartconfig { @bean multipartconfigelement multipartconfigelement() { multipartconfigfactory factory = new multipartconfigfactory(); string location = system.getproperty("user.dir") + "/data/tmp"; file tmpfile = new file(location); if (!tmpfile.exists()) { tmpfile.mkdirs(); } factory.setlocation(location); return factory.createmultipartconfig(); } }
4.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);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。