zoukankan      html  css  js  c++  java
  • 文件缓存类把文件放到缓存上

    // 从缓存读取数据

    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; } }
  • 相关阅读:
    无线电,电磁波
    ThinkPHP实现支付宝接口功能
    php中发送email
    编程基本功训练:流程图画法及练习
    PHP中的特殊类,接口类和抽象类(都不能直接实例化)
    PHP中面相对象对象的知识点整理
    memcache 与 mencached扩展的区别
    MVC框架 与Smarty
    浏览器缓存机制
    PHP中九大缓存技术总结
  • 原文地址:https://www.cnblogs.com/cuijinlong/p/8341721.html
Copyright © 2011-2022 走看看