報錯原因
-
臨時文件夾無效
在Spring Boot項目啟動后,系統會在‘/tmp’目錄下自動的創建幾個目錄:
tomcat.************.8088 tomcat-docbase.*********.8088
Multipart(form-data)的方式處理請求時,默認就是在第二個目錄下創建臨時文件的。
- 程序對文件的操作時:會生成臨時文件,暫存在臨時文件中;Linux系統的tmpwatch 命令會刪除10天未使用的臨時文件;長時間不進行上傳操作,導致/tmp下面的tomcat臨時文件目錄被刪除,且刪除的文件不可恢復,上傳文件時獲取不到文件目錄,導致報錯。
解決方法
- 方案1 修改tomcat啟動配置 添加
-Djava.io.tmpdir=
- 方案2
//1.該處也需要配置下 @SpringBootApplication(exclude = {MultipartAutoConfiguration.class}) public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication .class, args); } /** * 解決文件上傳,臨時文件夾被程序自動刪除問題 * * 文件上傳時自定義臨時路徑 * @return */ @Bean MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); //2.該處就是指定的路徑(需要提前創建好目錄,否則上傳時會拋出異常) factory.setLocation("/data/uploadtmp"); return factory.createMultipartConfig(); } }
- 方案三
CentOS6以下系統(含)使用watchtmp + cron來實現定時清理臨時文件的效果,這點在CentOS7發生了變化,在CentOS7下,系統使用systemd管理易變與臨時文件,與之相關的系統服務有3個:
systemd-tmpfiles-setup.service :Create Volatile Files and Directories systemd-tmpfiles-setup-dev.service:Create static device nodes in /dev systemd-tmpfiles-clean.service :Cleanup of Temporary Directories
相關的配置文件也有3個地方:
/etc/tmpfiles.d/*.conf /run/tmpfiles.d/*.conf /usr/lib/tmpfiles.d/*.conf
/tmp目錄的清理規則主要取決於/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 # 清理/tmp下10天前的目錄和文件 v /var/tmp 1777 root root 30d # 清理/var/tmp下30天前的目錄和文件 # 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
我們可以配置這個文件,比如你不想讓系統自動清理/tmp下以tomcat開頭的目錄,那么增加下面這條內容到配置文件中即可:
x /tmp/tomcat.*
更多配置內容參考:tmpfiles.d 中文手冊