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; } }
  • 相关阅读:
    SpringBoot中关于Shiro权限管理的整合使用
    Mybatis批处理(批量查询,更新,插入)
    Windows运行常用命令(win+R)
    IntelliJ IDEA中如何设置同时打开多个文件且分行显示?
    springboot的mybatis的xml相关的配置
    springbootl用thymeleaf整合htm
    resultMap的使用
    重识linux-linux主机上的用户信息传递
    重识linux-linux的新增与删除用户组和切换命令
    重识linux-linux的账号与用户组
  • 原文地址:https://www.cnblogs.com/cuijinlong/p/8341721.html
Copyright © 2011-2022 走看看