缓存Ehcache、Memcached、Redis的统一接口实现

本文介绍了如何在Java中创建一个统一接口,用于管理和操作Ehcache、Memcached和Redis这三种不同的缓存系统。通过该接口,开发者可以轻松地切换不同缓存技术,提高代码的可维护性和灵活性。
摘要由CSDN通过智能技术生成

接口

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) {
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值