java.io.IOException: The temporary upload location [/tmp/tomcat.1593253653386650830.8220/work/Tomcat/localhost/ROOT] is not valid
最近我们的几个服务有点问题: 本来好好的服务, 跑个10几天某些接口就调不通了返回500, 一看日志全是如上异常.
原因
Tomcat需要创建临时目录来存放上传的文件, 当POST请求的content-type是multipart/form-data的时候就会访问这个目录, 而这个目录在Linux系统中默认建在/tmp目录下, 10天就会被清除, 引发上述异常.
解决方法:
增加配置: server.tomcat.basedir=/yourpath/${spring.application.name} 这样就可以自定义临时目录
附代码
Tomcat.java
protected void initBaseDir() {
String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP);
if (basedir == null) {
basedir = System.getProperty(Globals.CATALINA_BASE_PROP);
}
if (basedir == null) {
basedir = catalinaHome;
}
if (basedir == null) {
// Create a temp dir.
basedir = System.getProperty("user.dir") +
"/tomcat." + port;
}
File baseFile = new File(basedir);
baseFile.mkdirs();
try {
baseFile = baseFile.getCanonicalFile();
} catch (IOException e) {
baseFile = baseFile.getAbsoluteFile();
}
server.setCatalinaBase(baseFile);
System.setProperty(Globals.CATALINA_BASE_PROP, baseFile.getPath());
basedir = baseFile.getPath();
if (catalinaHome == null) {
server.setCatalinaHome(baseFile);
} else {
File homeFile = new File(catalinaHome);
homeFile.mkdirs();
try {
homeFile = homeFile.getCanonicalFile();
} catch (IOException e) {
homeFile = homeFile.getAbsoluteFile();
}
server.setCatalinaHome(homeFile);
}
System.setProperty(Globals.CATALINA_HOME_PROP,
server.getCatalinaHome().getPath());
}
EmbeddedServletContainerFactory.java
public EmbeddedServletContainer getEmbeddedServletContainer(
ServletContextInitializer... initializers) {
Tomcat tomcat = new Tomcat();
File baseDir = (this.baseDirectory != null ? this.baseDirectory
: createTempDir("tomcat"));
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);
return getTomcatEmbeddedServletContainer(tomcat);
}
ServerProperties.java
@ConfigurationProperties(
prefix = "server",
ignoreUnknownFields = true
)
public class ServerProperties implements EmbeddedServletContainerCustomizer, EnvironmentAware, Ordered {
private File basedir;
void customizeTomcat(ServerProperties serverProperties, TomcatEmbeddedServletContainerFactory factory) {
if(this.getBasedir() != null) {
factory.setBaseDirectory(this.getBasedir());
}
}
}
网友评论