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

com.jeesuite.cache.local.GuavaLevel1CacheProvider Maven / Gradle / Ivy

There is a newer version: 1.4.0
Show newest version
/**
 * 
 */
package com.jeesuite.cache.local;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

/**
 * 本地缓存服务
 * @description 
* @author vakin * @date 2016年6月1日 */ public class GuavaLevel1CacheProvider implements Level1CacheProvider{ private static final String _NULL = "NULL"; private static final Logger logger = LoggerFactory.getLogger(GuavaLevel1CacheProvider.class); private Map> caches = new ConcurrentHashMap>(); private int maxSize = 10000; private int timeToLiveSeconds = 600; public void setMaxSize(int maxSize) { this.maxSize = maxSize; } public void setTimeToLiveSeconds(int timeToLiveSeconds) { this.timeToLiveSeconds = timeToLiveSeconds; } @Override public void start() { } public boolean set(String cacheName,String key,Object value){ if(value == null)return true; Cache cache = getCacheHolder(cacheName); if(cache != null){ cache.put(key, value); } return true; } @SuppressWarnings("unchecked") public T get(String cacheName,String key){ try { Cache cache = getCacheHolder(cacheName); if(cache != null){ Object result = cache.get(key, new Callable() { @Override public Object call() throws Exception { return _NULL; } }); if(result != null && !_NULL.equals(result)){ return (T)result; } } } catch (Exception e) { logger.warn("get LEVEL1 cache error",e); } return null; } public void remove(String cacheName,String key){ Cache cache = getCacheHolder(cacheName); if(cache != null){ cache.invalidateAll(); } } private Cache getCacheHolder(String cacheName){ return getAndNotexistsCreateCache(cacheName); } private Cache getAndNotexistsCreateCache(String cacheName){ Cache cache = caches.get(cacheName); if(cache != null)return cache; synchronized (caches) { if((cache = caches.get(cacheName)) != null)return cache; cache = CacheBuilder .newBuilder() .maximumSize(maxSize) .expireAfterWrite(timeToLiveSeconds, TimeUnit.SECONDS) .build(); caches.put(cacheName, cache); } return cache; } public void remove(String cacheName){ } public void clearAll(){ for (Cache cache : caches.values()) { cache.invalidateAll(); } } @Override public void close() throws IOException {} }