cache接口
public interface Cache {
<T> T get(Object key, Class<T> type);
boolean has(Object key);
void put(Object key, Object value);
void del(Object key);
}
cache工厂
public class CacheFactory {
private static class GuavaCache implements Cache {
private org.springframework.cache.Cache cache;
GuavaCache(String cacheName, int expiredMinutes) {
cache = new ConcurrentMapCache(cacheName,
CacheBuilder.newBuilder()
.expireAfterWrite(expiredMinutes, TimeUnit.MINUTES)
.build().asMap(),
false);
}
GuavaCache(String cacheName, int expiredTime, TimeUnit timeUnit) {
cache = new ConcurrentMapCache(cacheName,
CacheBuilder.newBuilder()
.expireAfterWrite(expiredTime, timeUnit)
.build().asMap(),
false);
}
@Override
public <T> T get(Object key, Class<T> type) {
return cache.get(key, type);
}
@Override
public boolean has(Object key) {
return cache.get(key) != null;
}
@Override
public void put(Object key, Object value) {
cache.put(key, value);
}
@Override
public void del(Object key) {
cache.put(key,"");
}
}
static private final String PREFIX = "CACHE_FACTORY_";
static private int sn = 1;
synchronized static public Cache getCacheWithExpiredMinutes(int expiredMinutes) {
String cacheName = PREFIX + sn;
sn += 1;
return new GuavaCache(cacheName, expiredMinutes);
}
synchronized static public Cache getCacheWithExpiredSeconds(int expiredSeconds) {
String cacheName = PREFIX + sn;
sn += 1;
return new GuavaCache(cacheName, expiredSeconds, TimeUnit.SECONDS);
}
}
使用
@Service
public class GuangPingDistributionDataHandler {
private Cache guangpingKeyWordListCache = CacheFactory.getCacheWithExpiredSeconds(10);
private static final String CACHEKEY = "guangpingCacheKey";
@Autowired
private DataToGuangPingAsynProducer dataToGuangPingAsynProducer;
@Autowired
private KeywordCommonRelationMapper keywordCommonRelationMapper;
@Override
Boolean isHitKeywords(List<String> keyWordList) {
List<String> giangPingKeyWordListFromCache = guangpingKeyWordListCache.get(CACHEKEY, List.class);
if (null == giangPingKeyWordListFromCache || giangPingKeyWordListFromCache.size() == 0) {
/** 如果没有缓存 **/
List<String> giangPingKeyWordListFromDB = keywordCommonRelationMapper.selectKeyListByValue(String.valueOf(SystemSourceEnum.GUANGPING.getCode()));
giangPingKeyWordListFromCache = giangPingKeyWordListFromDB;
guangpingKeyWordListCache.put(CACHEKEY, giangPingKeyWordListFromDB);
}
for(String keyWord : keyWordList){
if(giangPingKeyWordListFromCache.contains(keyWord)){
return true;
}
}
return false;
}
}