All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.ipokerface.weixin.cache.FileCacheStorager Maven / Gradle / Ivy

There is a newer version: 1.5.0
Show newest version
package cn.ipokerface.weixin.cache;

import java.io.*;

/**
 * Created by       PokerFace
 * Create Date      2019-12-27.
 * Email:           [email protected]
 * Version          1.0.0
 * 

* Description: */ public class FileCacheStorager implements AbstractCacheStorager { private final File tmpdir; public FileCacheStorager(){ this(System.getProperty("java.io.tmpdir")); } public FileCacheStorager(String folder){ this.tmpdir = new File(String.format("%s%s%s", folder, File.separator, "weixin_cache_keys")); this.tmpdir.mkdirs(); } @Override public T lookup(String key) { File cacheFile = new File(String.format("%s%s%s", tmpdir.getAbsolutePath(), File.separator, key)); ObjectInputStream inputStream = null; try { if (cacheFile.exists()) { inputStream = new ObjectInputStream(new FileInputStream(cacheFile)); T cache = (T)inputStream.readObject(); if (cache.createTime() < 0) { return cache; } if ((cache.createTime() + cache.expiredTime() - timeout) > System .currentTimeMillis()) { return cache; } } return null; } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e1){ throw new RuntimeException(e1); } finally { if (inputStream != null) try{inputStream.close();}catch (Exception e){} } } @Override public void caching(String key, T cache) { ObjectOutputStream outputStream = null; try { outputStream = new ObjectOutputStream(new FileOutputStream(new File(String.format("%s%s%s", tmpdir.getAbsolutePath(), File.separator, key)))); outputStream.writeObject(cache); outputStream.flush(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (outputStream != null) try{outputStream.close();}catch (Exception e){} } } @Override public T delete(String key) { File cacheFile = new File(String.format("%s%s%s", tmpdir.getAbsolutePath(), File.separator, key)); ObjectInputStream inputStream = null; try { if (cacheFile.exists()) { inputStream = new ObjectInputStream(new FileInputStream(cacheFile)); T cache = (T)inputStream.readObject(); cacheFile.delete(); return cache; } return null; } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e1){ throw new RuntimeException(e1); } finally { if (inputStream != null) try{inputStream.close();}catch (Exception e){} } } @Override public void clear() { for (File cache : tmpdir.listFiles()) { cache.delete(); } } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy