ehcache工具类

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

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

public class CacheBuilder {
	/**
	 * 日志
	 */
	private static final Logger LOGGER = LoggerFactory
			.getLogger(CacheBuilder.class);
	public static CacheBuilder instance = new CacheBuilder();
	public static CacheManager cacheManager;

	/**
	 * 添加缓存
	 * 
	 * @param cacheName
	 * @param key
	 * @param value
	 */
	public static void put(String cacheName, String key, Object value) {
		Ehcache cache = getCacheManager().getEhcache(cacheName);
		cache.put(new Element(key, value));
	}

	/**
	 * 根据缓存名与key获取值
	 * 
	 * @param cacheName
	 * @param key
	 * @return
	 */
	public static Object get(String cacheName, String key) {
		Ehcache cache = getCacheManager().getEhcache(cacheName);
		Element e = cache.get(key);
		return e == null ? null : e.getObjectValue();
	}

	public static Element getElement(String cacheName, String key) {
		Ehcache cache = getCacheManager().getEhcache(cacheName);
		Element e = cache.get(key);
		return e;
	}

	private static CacheManager getCacheManager() {
		if (cacheManager != null) {
			return cacheManager;
		}

		try {
			cacheManager = CacheManager.create();
		} catch (RuntimeException e) {
			LOGGER.error("init CacheBuilder failed", e);
			throw e;
		}
		return cacheManager;
	}
}

 

你可能感兴趣的:(ehcache)