接口
package com.enation.framework.cache;
/**
* 缓存接口
*
*/
public interface ICache<T> {
/**
* 初始化缓存对象
* @param cacheName 缓存对象名称
*/
public void initCache(String cacheName);
/**
* Get an item from the cache, nontransactionally
* @param key
* @return the cached object or <tt>null</tt>
* @throws CacheException
*/
public T get(Object key);
/**
* Add an item to the cache, nontransactionally, with
* failfast semantics
* @param key
* @param value
* @throws CacheException
*/
public void put(Object key, T value);
/**
* 往缓存中写入内容
* @param key
* @param value
* @param exp 超时时间,单位为秒
*/
public void put(Object key, T value, int exp);
/**
* Remove an item from the cache
*/
public void remove(Object key);
/**
* Clear the cache
*/
public void clear();
}
1、Ehcache的实现
package com.enation.framework.cache;
import java.io.Serializable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
* Ehcache缓存实现
*/
@Component
public class EhCacheImpl implements ICache {
private net.sf.ehcache.Cache cache;
/**
*
*/
public EhCacheImpl() { }
/**
* 初始化缓存对象
*
* @param name
*/
@Override
public void initCache(String name) {
try {
CacheManager manager = CacheManager.getInstance();
cache = manager.getCache(name);
if (cache == null) {
manager.addCache(name);
cache = manager.getCache(name);
}
} catch (net.sf.ehcache.CacheException e) {
e.printStackTrace();
}
}
/**
* Gets a value of an element which matches the given key.
*
* @param key
* the key of the element to return.
* @return The value placed into the cache with an earlier put, or null if
* not found or expired
* @throws CacheException
*/
public Object get(Object key) {
Object obj = null;
try {
if (key != null) {
Element element = cache.get((Serializable) key);
if (element != null) {
obj = element.getValue();
}
}
} catch (net.sf.ehcache.CacheException e) {