Created by yfyuan on 2017/2/4.
| 14 | * Created by yfyuan on 2017/2/4. |
| 15 | */ |
| 16 | public class EhCacheManager<T> implements CacheManager<T>, InitializingBean, DisposableBean { |
| 17 | |
| 18 | private static org.ehcache.CacheManager myCacheManager; |
| 19 | |
| 20 | private Cache<String, CacheObject> cache; |
| 21 | |
| 22 | private String cacheAlias; |
| 23 | |
| 24 | static { |
| 25 | final URL myUrl = EhCacheManager.class.getResource("/ehcache.xml"); |
| 26 | Configuration xmlConfig = new XmlConfiguration(myUrl); |
| 27 | myCacheManager = CacheManagerBuilder.newCacheManager(xmlConfig); |
| 28 | myCacheManager.init(); |
| 29 | } |
| 30 | |
| 31 | @Override |
| 32 | public void put(String key, T data, long expire) { |
| 33 | cache.put(key, new CacheObject(new Date().getTime(), expire, data)); |
| 34 | } |
| 35 | |
| 36 | @Override |
| 37 | public T get(String key) { |
| 38 | CacheObject o = cache.get(key); |
| 39 | if (o == null || new Date().getTime() >= o.getT1() + o.getExpire()) |
| 40 | return null; |
| 41 | else { |
| 42 | return (T) o.getD(); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | @Override |
| 47 | public void remove(String key) { |
| 48 | cache.remove(key); |
| 49 | } |
| 50 | |
| 51 | public void setCacheAlias(String cacheAlias) { |
| 52 | this.cacheAlias = cacheAlias; |
| 53 | } |
| 54 | |
| 55 | @Override |
| 56 | public void afterPropertiesSet() throws Exception { |
| 57 | cache = myCacheManager.getCache(cacheAlias, String.class, CacheObject.class); |
| 58 | } |
| 59 | |
| 60 | @Override |
| 61 | public void destroy() throws Exception { |
| 62 | EhCacheManager.myCacheManager.close(); |
| 63 | } |
| 64 | } |