Skip to content

Commit

Permalink
Delete Temporary Cache on shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
larsgrefer committed Aug 19, 2024
1 parent 45b1da4 commit f746480
Showing 1 changed file with 20 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import io.freefair.spring.okhttp.ApplicationInterceptor;
import io.freefair.spring.okhttp.NetworkInterceptor;
import io.freefair.spring.okhttp.OkHttp3Configurer;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -12,6 +14,7 @@
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.FileSystemUtils;

import javax.net.ssl.HostnameVerifier;
import java.io.File;
Expand All @@ -23,6 +26,7 @@
/**
* @author Lars Grefer
*/
@Slf4j
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@AutoConfiguration
@ConditionalOnClass(OkHttpClient.class)
Expand All @@ -43,6 +47,8 @@ public class OkHttp3AutoConfiguration {
@NetworkInterceptor
private ObjectProvider<Interceptor> networkInterceptors;

private File tempDirCache = null;

@Bean
@ConditionalOnMissingBean
public OkHttpClient okHttp3Client(
Expand Down Expand Up @@ -101,8 +107,21 @@ public ConnectionPool okHttp3ConnectionPool() {
public Cache okHttp3Cache() throws IOException {
File directory = okHttpProperties.getCache().getDirectory();
if (directory == null) {
directory = Files.createTempDirectory("okhttp-cache").toFile();
tempDirCache = Files.createTempDirectory("okhttp-cache").toFile();
directory = tempDirCache;
}
return new Cache(directory, okHttpProperties.getCache().getMaxSize().toBytes());
}

@PreDestroy
public void deleteTempCache() {
if (tempDirCache != null) {
log.debug("Deleting the temporary OkHttp Cache at {}", tempDirCache.getAbsolutePath());
try {
FileSystemUtils.deleteRecursively(tempDirCache);
} catch (Exception e) {
log.warn("Failed to delete the temporary OkHttp Cache at {}", tempDirCache.getAbsolutePath());
}
}
}
}

0 comments on commit f746480

Please sign in to comment.