// 从缓存读取数据
String vehicleData = FileCache.Get("vdata_"+cityId, 5);//5分钟失效
// 保存到缓存
FileCache.Set("vdata_"+cityId, m);
package net.joystart.common.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.joystart.common.util.date.DateSerializer;
import net.joystart.vehicle.service.impl.VehicleLock;
/***
* 文件缓存类
*
* @author lidongchun@bagechuxing.cn
*/
public class FileCache {
private static String cachePath = ConfigUtil.pro.get("cachePath")
.toString();
// 获取缓存文件内容
public static String Get(String key, int ttl) {
try {
String fileName = cachePath + "/" + key;
String encoding = "UTF-8";
File file = new File(fileName);
long from = file.lastModified();
long to = new Date().getTime();
int minutes = (int) ((to - from) / 1000);
if (minutes > ttl) {
return null;
}
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
FileInputStream in = new FileInputStream(file);
in.read(filecontent);
in.close();
return new String(filecontent, encoding);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 设置缓存文件内容
public static boolean Set(String key, Object content) {
VehicleLock lock = new VehicleLock(key);
if (content instanceof String == false) {
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);
Gson gson = gb.create();
content = gson.toJson(content);
}
final String fileContent = String.valueOf(content);
lock.wrap(new Runnable() {
@Override
public void run() {
try {
String pathname = cachePath + "/" + key;
BufferedWriter out = new BufferedWriter(new FileWriter(
pathname));
out.write(fileContent);
out.close();
} catch (IOException e) {
}
}
});
return true;
}
}