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

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

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

import cn.ipokerface.weixin.exception.WeixinException;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

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

* Description: */ public class CacheManager { protected final CacheCreator cacheCreator; protected final AbstractCacheStorager cacheStorager; private final ReentrantLock lock = new ReentrantLock(); public CacheManager(CacheCreator cacheCreator, AbstractCacheStorager cacheStorager) { this.cacheCreator = cacheCreator; this.cacheStorager = cacheStorager; } /** * 获取缓存对象 * * @return 缓存对象 * @throws WeixinException */ public T getCache() throws WeixinException { String cacheKey = cacheCreator.key(); T cache = cacheStorager.lookup(cacheKey); try { if (cache == null && lock.tryLock(3, TimeUnit.SECONDS)) { try { cache = cacheStorager.lookup(cacheKey); if (cache == null) { cache = cacheCreator.create(); cacheStorager.caching(cacheKey, cache); } } finally { lock.unlock(); } } } catch (InterruptedException e) { throw new WeixinException("get cache error on lock", e); } return cache; } /** * 刷新缓存对象 * * @return 缓存对象 * @throws WeixinException */ public T refreshCache() throws WeixinException { String cacheKey = cacheCreator.key(); T cache = cacheCreator.create(); cacheStorager.caching(cacheKey, cache); return cache; } /** * 移除缓存 * * @return 被移除的缓存对象 */ public T evictCache() { String cacheKey = cacheCreator.key(); return cacheStorager.delete(cacheKey); } /** * 清除所有的缓存(请慎重) */ public void clearCache() { cacheStorager.clear(); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy