redis不能直接保存localDateTime对象,需要转为String类型,否则从redis中取出再和localDateTime比对是,即使转为localDateTime比对,也会失败。
// 计算文件名的哈希码(注意:这里使用文件名而不是文件路径)
int hashCode = filename.hashCode();
// 获取当前时间
LocalDateTime currentTime = LocalDateTime.now();
Map<String, Map<String, Object>> uploadFilePath = new HashMap<>();
if(redisTemplate.hasKey("upload_file_path")){
uploadFilePath = redisCache.getCacheMap("upload_file_path");
}
// 创建一个 DateTimeFormatter 对象,指定格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 使用 formatter 将 LocalDateTime 转换为 String
String formattedDateTime = currentTime.format(formatter);
// 创建存储对象(使用 HashMap)
Map<String, Object> data = new HashMap<>();
data.put("filepath", filename);
data.put("timestamp", formattedDateTime);
// 使用 HashMap 来存储文件名哈希码到数据的映射
uploadFilePath.put(String.valueOf(hashCode), data); // 使用 String.valueOf 确保键是 String 类型
// 调用 setCacheMap 方法存储数据到 Redis 中
redisCache.setCacheMap("upload_file_path", uploadFilePath);
// removeFileNameFromRedis(filename,true);
从redis中取出进行比对,超过多久的文件需要从redis中删除,并从文件系统Minio中删除附件
/**
*如果资源提交了,从redis 中移除文件名
* @param filename 文件路径
* @param boolean isremove 是否需要删除,资源删除成功了,需要从redis中清除记录
*/
public void removeFileNameFromRedis(String filename,boolean isremove){
int hashCode = filename.hashCode();
String key = String.valueOf(hashCode);
Map<String, Map<String, Object>> uploadFilePath = redisCache.getCacheMap("upload_file_path");
Map<String, Object> data = uploadFilePath.get(key);
String timestampStr = (String) data.get("timestamp");
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
try {
// 解析起始日期时间
LocalDateTime timestamp = LocalDateTime.parse(timestampStr, dateTimeFormatter);
System.out.println("文件时间========="+timestamp);
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("当前时间====="+LocalDateTime.now());
// 计算时间差
Duration duration = Duration.between(timestamp, LocalDateTime.now());
//超过60分钟,从redis中删除
if (duration.toMinutes() > 60) {
//redisCache.delCacheMapValue("upload_file_path", key);
removeUploadFileFromRedisCache(key);
} else {
System.out.println("文件未超时");
}
} catch (DateTimeParseException e) {
System.err.println("日期时间格式错误: " + e.getMessage());
}
if(isremove) {
//删除附件
String filepath = data.get("filepath").toString();
deleteFileFromMinio(filepath);
}
}