Skip to content

Commit

Permalink
缓存自动清理任务支持 对多久前创建的文件进行删除的选项
Browse files Browse the repository at this point in the history
  • Loading branch information
wlplove007 committed Mar 25, 2023
1 parent b7ed284 commit 866f5e6
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 1 deletion.
2 changes: 2 additions & 0 deletions server/src/main/config/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ spring.redisson.password = ${KK_SPRING_REDISSON_PASSWORD:}
cache.clean.enabled = ${KK_CACHE_CLEAN_ENABLED:true}
#缓存自动清理时间cache.clean.enabled = true时才有用cron表达式基于Quartz cron
cache.clean.cron = ${KK_CACHE_CLEAN_CRON:0 0 3 * * ?}
#缓存自动清理任务清理n小时前创建的文件0为清理所有
cache.clean.hour = ${KK_CACHE_CLEAN_HOUR:1}

#######################################可在运行时动态配置#######################################
#提供预览服务的地址默认从请求url读如果使用nginx等反向代理需要手动设置
Expand Down
10 changes: 9 additions & 1 deletion server/src/main/java/cn/keking/config/SchedulerCleanConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import cn.keking.utils.KkFileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
Expand All @@ -26,12 +27,19 @@ public SchedulerCleanConfig(CacheService cacheService) {

private final String fileDir = ConfigConstants.getFileDir();

private int hour;

@Value("${cache.clean.hour:0}")
public void setHour(String hour) {
this.hour = Integer.parseInt(hour);
}

//默认每晚3点执行一次
@Scheduled(cron = "${cache.clean.cron:0 0 3 * * ?}")
public void clean() {
logger.info("Cache clean start");
cacheService.cleanCache();
KkFileUtils.deleteDirectory(fileDir);
KkFileUtils.cleanDirectory(fileDir, hour * 3600000L);
logger.info("Cache clean end");
}
}
57 changes: 57 additions & 0 deletions server/src/main/java/cn/keking/utils/KkFileUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
import org.springframework.web.util.HtmlUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
Expand Down Expand Up @@ -174,4 +178,57 @@ public static boolean deleteDirectory(String dir) {
return true;
}


/**
* 清空目录
*
* @param dir 要清空的目录路径
* @param millis 要删除多久前的文件夹/文件,0全删,单位ms
* @return 目录清空成功返回true,否则返回false
*/
public static boolean cleanDirectory(String dir, long millis) {
// 如果dir不以文件分隔符结尾,自动添加文件分隔符
if (!dir.endsWith(File.separator)) {
dir = dir + File.separator;
}
File dirFile = new File(dir);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
LOGGER.info("清空目录失败:" + dir + "不存在!");
return false;
}
boolean flag = true;
// 清空文件夹中的文件包括子目录
File[] files = dirFile.listFiles();
for (int i = 0; i < Objects.requireNonNull(files).length; i++) {
try {
BasicFileAttributes attrs = Files.readAttributes(Paths.get(files[i].getAbsolutePath()),
BasicFileAttributes.class);
if (millis > 0 && System.currentTimeMillis() - attrs.creationTime().toMillis() < millis) {
continue;
}
} catch (IOException e) {
LOGGER.error("读取创建时间失败");
}
// 删除子文件
if (files[i].isFile()) {
flag = KkFileUtils.deleteFileByName(files[i].getAbsolutePath());
if (!flag) {
break;
}
} else if (files[i].isDirectory()) {
// 删除子目录
flag = KkFileUtils.deleteDirectory(files[i].getAbsolutePath());
if (!flag) {
break;
}
}
}
if (!flag) {
LOGGER.info("清空目录失败!");
return false;
}
return true;
}

}

0 comments on commit 866f5e6

Please sign in to comment.