背景
我们在工作中可能会遇到这样的场景,我们需要定时获取获取一个对象。但这个对象比较大,数量比较多。缓存在redis,数据库里面都不太合适。这个时候我们可以考虑将文件缓存本地文件当中。
代码
1、配置文件文件缓存路径
在application.properties中添加
fileCacheDir=C:\\Users\\Administrator\\Desktop\\deploy
2、设置文件缓存路径
@Configuration
public class FileCacheConfig {
@Value("${fileCacheDir}")
private String fileCacheDir;
@Bean
public FileCache getFileCache(){
return new FileCache(fileCacheDir);
}
}
3、操作文件缓存对象
接口
public interface ICache {
/**
* 根据key获取缓存数据
* @param key 存储key
* @return 缓存到文件中的数据
*/
<T> T get(String key) throws IOException, ClassNotFoundException, Exception;
/**
* 添加缓存
* @param key 存储key
* @param data 缓存到文件中的数据
*/
int set(String key, Object data) throws IOException;
/**
* 删除
* @return 删除影响的行数
*/
int delete(String key);
}
具体操作类:
public class FileCache implements ICache {
private String cacheDir;
public FileCache(String cacheDir) {
this.cacheDir = cacheDir;
}
@Override
public Object get(String key) throws Exception {
File file = new File(this.getRealFilePath(key));
if (!file.exists()) {
return null;
}
//获取文件中对象
Object fileObject = FileOperate.getFileObject(file);
Object fileStorageObject = null;
if ( fileObject instanceof FileCacheObject) {
FileCacheObject fcObject = (FileCacheObject)fileObject;
//查看缓存是否过期
if (!fcObject.isCacheExpire()) {
fileStorageObject = fcObject.getStorageObject();
}
}
//如果不存在活已经过期就删除
if (null == fileStorageObject) {
file.delete();
}
return fileStorageObject;
}
@Override
public int set(String key, Object data) throws IOException {
String filePath = this.getRealFilePath(key);
return FileOperate.saveObjectToFile(filePath, new FileCacheO