1 package com.foxinmy.weixin4j.cache;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7
8 import com.foxinmy.weixin4j.util.SerializationUtils;
9
10
11
12
13
14
15
16
17
18
19 public class FileCacheStorager<T extends Cacheable> implements CacheStorager<T> {
20
21 private final File tmpdir;
22 private final String SEPARATOR = File.separator;
23
24
25
26
27 public FileCacheStorager() {
28 this(System.getProperty("java.io.tmpdir"));
29 }
30
31
32
33
34
35
36 public FileCacheStorager(String path) {
37 this.tmpdir = new File(String.format("%s%s%s", path, SEPARATOR, ALLKEY));
38 this.tmpdir.mkdirs();
39 }
40
41 @Override
42 public T lookup(String key) {
43 File cacheFile = new File(String.format("%s%s%s",
44 tmpdir.getAbsolutePath(), SEPARATOR, key));
45 try {
46 if (cacheFile.exists()) {
47 T cache = SerializationUtils.deserialize(new FileInputStream(
48 cacheFile));
49 if (cache.getExpires() < 0l) {
50 return cache;
51 }
52 if ((cache.getCreateTime() + cache.getExpires() - CUTMS) > System
53 .currentTimeMillis()) {
54 return cache;
55 }
56 }
57 return null;
58 } catch (IOException e) {
59 throw new RuntimeException(e);
60 }
61 }
62
63 @Override
64 public void caching(String key, T cache) {
65 try {
66 SerializationUtils.serialize(
67 cache,
68 new FileOutputStream(new File(String.format("%s%s%s",
69 tmpdir.getAbsolutePath(), SEPARATOR, key))));
70 } catch (IOException e) {
71 throw new RuntimeException(e);
72 }
73 }
74
75 @Override
76 public T evict(String key) {
77 T cache = null;
78 File cacheFile = new File(String.format("%s%s%s",
79 tmpdir.getAbsolutePath(), SEPARATOR, key));
80 try {
81 if (cacheFile.exists()) {
82 cache = SerializationUtils.deserialize(new FileInputStream(
83 cacheFile));
84 cacheFile.delete();
85 }
86 } catch (IOException e) {
87 ;
88 }
89 return cache;
90 }
91
92 @Override
93 public void clear() {
94 for (File cache : tmpdir.listFiles()) {
95 cache.delete();
96 }
97 }
98 }