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

来源:互联网 发布:java打印金字塔 编辑:程序博客网 时间:2024/05/16 08:47

接口

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缓存实现 */@Componentpublic class EhCacheImpl implements ICache {private net.sf.ehcache.Cache cache;/** *  */public EhCacheImpl() { }/** * 初始化缓存对象 *  * @param name */@Overridepublic 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) {e.printStackTrace();}return obj;}/** * Puts an object into the cache. *  * @param key *            a {@link Serializable} key * @param value *            a {@link Serializable} value * @throws CacheException *             if the parameters are not {@link Serializable}, the *             {@link CacheManager} is shutdown or another {@link Exception} *             occurs. */public void put(Object key, Object value) {try {Element element = new Element((Serializable) key,(Serializable) value);cache.put(element);} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalStateException e) {e.printStackTrace();}}/** * Puts an object into the cache. * @param key * @param value * @param exp */public void put(Object key, Object value, int exp) {try {Element element = new Element((Serializable) key,(Serializable) value);element.setTimeToLive(exp);cache.put(element);} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalStateException e) {e.printStackTrace();}}/** * Removes the element which matches the key. * <p> * If no element matches, nothing is removed and no Exception is thrown. *  * @param key *            the key of the element to remove * @throws CacheException */public void remove(Object key) {try {cache.remove((Serializable) key);} catch (ClassCastException e) {e.printStackTrace();} catch (IllegalStateException e) {e.printStackTrace();}}public static void main(String[] args) {EhCacheImpl cache = new EhCacheImpl();cache.initCache("queryCache"); cache.put("test","fjdkafjsdkajd");}@Overridepublic void clear() { try {        //cache.remove(arg0)            cache.removeAll();        } catch (IllegalStateException e) {        e.printStackTrace();        } }}

2、Memcached的实现

package com.enation.app.shop.cluster.cache.memcached;import java.io.IOException;import java.util.concurrent.TimeoutException;import org.apache.commons.lang3.StringUtils;import org.apache.log4j.Logger;import org.springframework.stereotype.Component;import com.enation.framework.cache.ICache;import com.enation.framework.util.PropertiesUtil;import net.rubyeye.xmemcached.XMemcachedClient;import net.rubyeye.xmemcached.XMemcachedClientBuilder;import net.rubyeye.xmemcached.exception.MemcachedException;import net.rubyeye.xmemcached.utils.AddrUtil;/** * Memcached的缓存实现 */@Componentpublic class MemcachedImpl implements ICache {protected final Logger logger = Logger.getLogger(getClass());private static XMemcachedClient memcachedClient;@Overridepublic void initCache(String cacheName) {if (memcachedClient != null)return;try {PropertiesUtil properties = new PropertiesUtil("cluster.properties");String memcachedServer = properties.getProperties("memcached_server");if(StringUtils.isEmpty(memcachedServer)){logger.error("can't get memcached server address");return;}String[] memcachedServers = StringUtils.split(memcachedServer, ",");XMemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(memcachedServers[0]));memcachedClient = (XMemcachedClient) builder.build();if(memcachedServers.length > 1){for(int i = 1; i < memcachedServers.length; i++){try{memcachedClient.addServer(memcachedServers[i].trim());}catch(Exception ex){logger.error("can't connect " + memcachedServers[i].trim(), ex);}}}} catch (IOException ex) {logger.error("can't conect memcached server", ex);}}@Overridepublic Object get(Object key) {try {return memcachedClient.get(key.toString());} catch (TimeoutException | InterruptedException | MemcachedException e) {logger.error("get cache from memcached error", e);}return null;}@Overridepublic void put(Object key, Object value) {try {memcachedClient.set(key.toString(), 0, value);} catch (TimeoutException | InterruptedException | MemcachedException e) {logger.error("put value to memcached error", e);}}@Overridepublic void put(Object key, Object value, int exp) {try {memcachedClient.set(key.toString(), exp, value);} catch (TimeoutException | InterruptedException | MemcachedException e) {logger.error("put value to memcached error", e);}}@Overridepublic void remove(Object key) {try {memcachedClient.delete(key.toString());} catch (TimeoutException | InterruptedException | MemcachedException e) {logger.error("remove cache from memcached error", e);}}@Overridepublic void clear() {// TODO Auto-generated method stub}}

3、Redis的实现

package com.enation.app.shop.cluster.cache.redis;import java.util.ArrayList;import java.util.List;import org.apache.commons.lang3.StringUtils;import org.apache.commons.lang3.math.NumberUtils;import org.apache.log4j.Logger;import org.springframework.stereotype.Component;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;import redis.clients.jedis.JedisShardInfo;import redis.clients.jedis.ShardedJedis;import redis.clients.jedis.ShardedJedisPool;import com.enation.app.base.core.model.Member;import com.enation.framework.cache.ICache;import com.enation.framework.util.PropertiesUtil;import com.enation.framework.util.SerializeUtil;/** * Redis的缓存实现类 * */@Componentpublic class RedisImpl implements ICache {protected final Logger logger = Logger.getLogger(getClass());private static ShardedJedisPool pool;@Overridepublic void initCache(String cacheName) {if (pool != null)return;PropertiesUtil properties = new PropertiesUtil("cluster.properties");String redisServer = properties.getProperties("redis_server");if(StringUtils.isEmpty(redisServer)){logger.error("can't get redis server address");return;}String[] redisServers = StringUtils.split(redisServer, ",");          List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();        for(int i = 0; i < redisServers.length; i++){        String[] hostPort = StringUtils.split(redisServers[i].trim(), ":");        String host = hostPort[0];        int port = 6379;        if(hostPort.length == 2){        port = NumberUtils.toInt(hostPort[1], 6379);        }        try{        shards.add(new JedisShardInfo(host, port, "redis_" + i));        }catch(Exception ex){        logger.error("can't connect " + redisServers[i].trim(), ex);        }        }        // 构造池          pool = new ShardedJedisPool(new JedisPoolConfig(), shards);}@Overridepublic Object get(Object key) {ShardedJedis shardedJedis = null;try {shardedJedis = pool.getResource();byte[] bytes = shardedJedis.get(key.toString().getBytes());if (bytes == null || bytes.length == 0)return null;return SerializeUtil.unserialize(bytes);} catch (Exception ex) {logger.error("get cache from redis error", ex);} finally {if (shardedJedis != null) {pool.returnResource(shardedJedis);}}return null;}@Overridepublic void put(Object key, Object value) {ShardedJedis shardedJedis = null;try {shardedJedis = pool.getResource();shardedJedis.set(key.toString().getBytes(), SerializeUtil.serialize(value));} catch (Exception ex) {logger.error("put cache to redis error", ex);} finally {if (shardedJedis != null) {pool.returnResource(shardedJedis);}}}@Overridepublic void put(Object key, Object value, int exp) {ShardedJedis shardedJedis = null;try {shardedJedis = pool.getResource();shardedJedis.setex(key.toString().getBytes(), exp, SerializeUtil.serialize(value));} catch (Exception ex) {logger.error("put cache to redis error", ex);} finally {if (shardedJedis != null) {pool.returnResource(shardedJedis);}}}@Overridepublic void remove(Object key) {ShardedJedis shardedJedis = null;try {shardedJedis = pool.getResource();shardedJedis.del(key.toString().getBytes());} catch (Exception ex) {logger.error("remove cache from redis error", ex);} finally {if (shardedJedis != null) {pool.returnResource(shardedJedis);}}}public static void main(String[] args) {JedisPool pool2 = new JedisPool(new JedisPoolConfig(), "localhost");Jedis jedis = null;try {jedis = pool2.getResource();Member m = new Member();m.setUname("dawei");jedis.set("user".getBytes(), SerializeUtil.serialize(m));// String name = jedis.get("user");// System.out.println(name);Member m1 = (Member) SerializeUtil.unserialize(jedis.get("user".getBytes()));System.out.println(m1.getUname());} catch (Exception ex) {ex.printStackTrace();} finally {if (jedis != null) {jedis.close();}}}@Overridepublic void clear() {// TODO Auto-generated method stub}}


0 0
原创粉丝点击