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

com.lone.common.core.cache.FlowEhcache Maven / Gradle / Ivy

The newest version!
package com.lone.common.core.cache;

import java.util.List;

import org.springframework.util.Assert;

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

public class FlowEhcache implements Cache {
	private Ehcache cache;// ehcache

	public FlowEhcache(Ehcache cache) {
		Assert.notNull(cache, "cache is not null");
		this.cache = CacheManager.getInstance().getCache("flowCache");// 永久缓存块
	}

	/**
	 * {@inheritDoc}
	 */
	public Object getObject(Object key) {
		try {
			Element cachedElement = cache.get(key);
			if (cachedElement == null) {
				return null;
			}
			return cachedElement.getObjectValue();
		} catch (Throwable t) {
			throw new CacheException(t);
		}
	}

	@Override
	public Object getItem(String key) {
		try {
			Element cachedElement = cache.get(key);
			if (cachedElement == null) {
				return null;
			}
			return cachedElement.getObjectValue();
		} catch (Throwable t) {
			throw new CacheException(t);
		}
	}

	@Override
	public void putItem(String key, Object value) {
		try {
			cache.put(new Element(key, value));
		} catch (Throwable t) {
			throw new CacheException(t);
		}
	}

	public List getAllItem() {
		try {
			// 获取所有的缓存对象
			@SuppressWarnings("unchecked")
			List allItem = cache.getKeys();

			return allItem;
		} catch (Throwable t) {
			throw new CacheException(t);
		}
	}

	@Override
	public Object removeItem(String key) {
		try {
			Object obj = this.getObject(key);
			this.cache.remove(key);
			return obj;
		} catch (Throwable t) {
			throw new CacheException(t);
		}
	}

	@Override
	public void cleanItem(String key) {
		try {
			this.cache.remove(key);
		} catch (Throwable t) {
			throw new CacheException(t);
		}
	}

	@Override
	public void removeAll() {
		try {
			this.cache.removeAll();
		} catch (Throwable t) {
			throw new CacheException(t);
		}
	}

}