zoukankan      html  css  js  c++  java
  • redis(五)redis与Mybatis的无缝整合让MyBatis透明的管理缓存二

    在上一篇文中的Cahe类存在各种问题如:一直使用同一个连接,每次都创建新的Cache,项目中老是爆出connection timeout 的异常,存储的key过长等等一系列的问题,解决问题最好的办法就是看源码和看官方的文档说明,jedis的文档还是够用的,接下来把cache也改造以下附上代码。

    Java代码  收藏代码
    1. package cn.seafood.cache;  
    2.   
    3. import java.io.ByteArrayInputStream;  
    4. import java.io.ByteArrayOutputStream;  
    5. import java.io.ObjectInputStream;  
    6. import java.io.ObjectOutputStream;  
    7. import java.util.concurrent.locks.ReadWriteLock;  
    8. import java.util.concurrent.locks.ReentrantReadWriteLock;  
    9.   
    10. import org.apache.commons.logging.Log;  
    11. import org.apache.commons.logging.LogFactory;  
    12. import org.apache.ibatis.cache.Cache;  
    13.   
    14. import redis.clients.jedis.Jedis;  
    15. import redis.clients.jedis.JedisPool;  
    16. import redis.clients.jedis.JedisPoolConfig;  
    17. import redis.clients.jedis.exceptions.JedisConnectionException;  
    18. import cn.seafood.util.PropertiesLoader;  
    19.   
    20. /** 
    21.  *  
    22. * @ClassName: RedisCache 
    23. * @Description: TODO(使用第三方缓存服务器redis,处理二级缓存) 
    24. * @author LiuYi 
    25. * @date 2014年6月9日 下午1:37:46 
    26. * 
    27.  */  
    28. public class RedisCache   implements Cache {  
    29.         private static Log log = LogFactory.getLog(RedisCache.class);  
    30.         /** The ReadWriteLock. */  
    31.         private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();  
    32.           
    33.         private String id;  
    34.         public RedisCache(final String id) {  
    35.                 if (id == null) {  
    36.                         throw new IllegalArgumentException("必须传入ID");  
    37.                 }  
    38.                 log.debug("MybatisRedisCache:id=" + id);  
    39.                 this.id=id;  
    40.         }  
    41.           
    42.         @Override  
    43.         public String getId() {  
    44.                 return this.id;  
    45.         }  
    46.   
    47.         @Override  
    48.         public int getSize() {  
    49.                 Jedis jedis = null;  
    50.                 JedisPool jedisPool = null;  
    51.                 int result = 0;  
    52.                 boolean borrowOrOprSuccess = true;  
    53.                 try {  
    54.                         jedis   = CachePool.getInstance().getJedis();  
    55.                         jedisPool = CachePool.getInstance().getJedisPool();  
    56.                         result = Integer.valueOf(jedis.dbSize().toString());  
    57.                 } catch (JedisConnectionException e) {  
    58.                         borrowOrOprSuccess = false;  
    59.                         if (jedis != null)  
    60.                                 jedisPool.returnBrokenResource(jedis);  
    61.                 } finally {  
    62.                         if (borrowOrOprSuccess)  
    63.                                 jedisPool.returnResource(jedis);  
    64.                 }  
    65.                 return result;  
    66.                    
    67.         }  
    68.   
    69.         @Override  
    70.         public void putObject(Object key, Object value) {  
    71.                 if(log.isDebugEnabled())  
    72.                 log.debug("putObject:" + key.hashCode() + "=" + value);  
    73.                 if(log.isInfoEnabled())  
    74.                 log.info("put to redis sql :" +key.toString());  
    75.                 Jedis jedis = null;  
    76.                 JedisPool jedisPool = null;  
    77.                 boolean borrowOrOprSuccess = true;  
    78.                 try {  
    79.                         jedis   = CachePool.getInstance().getJedis();  
    80.                         jedisPool = CachePool.getInstance().getJedisPool();  
    81.                         jedis.set(SerializeUtil.serialize(key.hashCode()), SerializeUtil.serialize(value));  
    82.                 } catch (JedisConnectionException e) {  
    83.                         borrowOrOprSuccess = false;  
    84.                         if (jedis != null)  
    85.                                 jedisPool.returnBrokenResource(jedis);  
    86.                 } finally {  
    87.                         if (borrowOrOprSuccess)  
    88.                                 jedisPool.returnResource(jedis);  
    89.                 }  
    90.                   
    91.         }  
    92.   
    93.         @Override  
    94.         public Object getObject(Object key) {  
    95.                 Jedis jedis = null;  
    96.                 JedisPool jedisPool = null;  
    97.                 Object value = null;  
    98.                 boolean borrowOrOprSuccess = true;  
    99.                 try {  
    100.                         jedis   = CachePool.getInstance().getJedis();  
    101.                         jedisPool = CachePool.getInstance().getJedisPool();  
    102.                         value  = SerializeUtil.unserialize(jedis.get(SerializeUtil.serialize(key.hashCode())));  
    103.                 } catch (JedisConnectionException e) {  
    104.                         borrowOrOprSuccess = false;  
    105.                         if (jedis != null)  
    106.                                 jedisPool.returnBrokenResource(jedis);  
    107.                 } finally {  
    108.                         if (borrowOrOprSuccess)  
    109.                                 jedisPool.returnResource(jedis);  
    110.                 }  
    111.                 if(log.isDebugEnabled())  
    112.                 log.debug("getObject:" + key.hashCode() + "=" + value);  
    113.                 return value;  
    114.         }  
    115.   
    116.         @Override  
    117.         public Object removeObject(Object key) {  
    118.                 Jedis jedis = null;  
    119.                 JedisPool jedisPool = null;  
    120.                 Object value = null;  
    121.                 boolean borrowOrOprSuccess = true;  
    122.                 try {  
    123.                         jedis   = CachePool.getInstance().getJedis();  
    124.                         jedisPool = CachePool.getInstance().getJedisPool();  
    125.                         value  = jedis.expire(SerializeUtil.serialize(key.hashCode()), 0);  
    126.                 } catch (JedisConnectionException e) {  
    127.                         borrowOrOprSuccess = false;  
    128.                         if (jedis != null)  
    129.                                 jedisPool.returnBrokenResource(jedis);  
    130.                 } finally {  
    131.                         if (borrowOrOprSuccess)  
    132.                                 jedisPool.returnResource(jedis);  
    133.                 }  
    134.                 if(log.isDebugEnabled())  
    135.                 log.debug("getObject:" + key.hashCode() + "=" + value);  
    136.                 return value;  
    137.         }  
    138.   
    139.         @Override  
    140.         public void clear() {  
    141.                 Jedis jedis = null;  
    142.                 JedisPool jedisPool = null;  
    143.                 boolean borrowOrOprSuccess = true;  
    144.                 try {  
    145.                         jedis   = CachePool.getInstance().getJedis();  
    146.                         jedisPool = CachePool.getInstance().getJedisPool();  
    147.                         jedis.flushDB();  
    148.                         jedis.flushAll();  
    149.                 } catch (JedisConnectionException e) {  
    150.                         borrowOrOprSuccess = false;  
    151.                         if (jedis != null)  
    152.                                 jedisPool.returnBrokenResource(jedis);  
    153.                 } finally {  
    154.                         if (borrowOrOprSuccess)  
    155.                                 jedisPool.returnResource(jedis);  
    156.                 }  
    157.         }  
    158.   
    159.         @Override  
    160.         public ReadWriteLock getReadWriteLock() {  
    161.                 return readWriteLock;  
    162.         }  
    163.        /** 
    164.         *  
    165.        * @ClassName: CachePool 
    166.        * @Description: TODO(单例Cache池) 
    167.        * @author LiuYi 
    168.        * @date 2014年6月17日 上午10:50:52 
    169.        * 
    170.         */  
    171.         public static class CachePool {  
    172.                 JedisPool pool;  
    173.                 private static final CachePool cachePool = new CachePool();  
    174.                   
    175.                 public static CachePool getInstance(){  
    176.                         return cachePool;  
    177.                 }  
    178.                 private CachePool() {  
    179.                         JedisPoolConfig config = new JedisPoolConfig();  
    180.                         config.setMaxIdle(100);  
    181.                         config.setMaxWaitMillis(1000l);  
    182.                          PropertiesLoader pl =  new PropertiesLoader("classpath:config/redis.properties");  
    183.                          pool = new JedisPool(config,pl.getProperty("redisvip"));  
    184.                 }  
    185.                 public  Jedis getJedis(){  
    186.                         Jedis jedis = null;  
    187.                         boolean borrowOrOprSuccess = true;  
    188.                         try {  
    189.                                 jedis = pool.getResource();  
    190.                         } catch (JedisConnectionException e) {  
    191.                                 borrowOrOprSuccess = false;  
    192.                                 if (jedis != null)  
    193.                                         pool.returnBrokenResource(jedis);  
    194.                         } finally {  
    195.                                 if (borrowOrOprSuccess)  
    196.                                         pool.returnResource(jedis);  
    197.                         }  
    198.                         jedis = pool.getResource();  
    199.                         return jedis;  
    200.                 }  
    201.                   
    202.                 public JedisPool getJedisPool(){  
    203.                         return this.pool;  
    204.                 }  
    205.                   
    206.         }  
    207.           
    208.           
    209.         public static class SerializeUtil {  
    210.                 public static byte[] serialize(Object object) {  
    211.                         ObjectOutputStream oos = null;  
    212.                         ByteArrayOutputStream baos = null;  
    213.                         try {  
    214.                                 // 序列化  
    215.                                 baos = new ByteArrayOutputStream();  
    216.                                 oos = new ObjectOutputStream(baos);  
    217.                                 oos.writeObject(object);  
    218.                                 byte[] bytes = baos.toByteArray();  
    219.                                 return bytes;  
    220.                         } catch (Exception e) {  
    221.                                 e.printStackTrace();  
    222.                         }  
    223.                         return null;  
    224.                 }  
    225.   
    226.                 public static Object unserialize(byte[] bytes) {  
    227.                         if(bytes == null)return null;  
    228.                         ByteArrayInputStream bais = null;  
    229.                         try {  
    230.                                 // 反序列化  
    231.                                 bais = new ByteArrayInputStream(bytes);  
    232.                                 ObjectInputStream ois = new ObjectInputStream(bais);  
    233.                                 return ois.readObject();  
    234.                         } catch (Exception e) {  
    235.                                 e.printStackTrace();  
    236.                         }  
    237.                         return null;  
    238.                 }  
    239.         }  
    240. }  
  • 相关阅读:
    正式定居博客圆,发些以前在Topcoder上的练习题,对算法和STL有兴趣的朋友可以看下:)
    TopCoder真题讲解之二
    “命名空间“System”中不存在类型或命名空间名称“Linq”(是缺少程序集引用吗?)”
    短信发送
    JavaScript打印和预览等
    .net获取IP地址的几种方法转载
    WinForm中控件与背景透明
    用C#实现C/S模式下软件自动在线升级转
    Microsoft Access 时间函数汇总
    .net 发送Email 单发 群发
  • 原文地址:https://www.cnblogs.com/duyinqiang/p/5696406.html
Copyright © 2011-2022 走看看