redis+mybatis+spring

来源:互联网 发布:spu sku 数据库设计 编辑:程序博客网 时间:2024/06/03 20:43

redis的安装http://liuyieyer.iteye.com/blog/2078093

redis的主从高可用 http://liuyieyer.iteye.com/blog/2078095

Mybatis 的使用不多说。

Mybatis为了方便我们扩展缓存定义了一个Cache接口,看看ehcache-mybatis的源码就明白了。我们要使用自己的cache同样的实现Cache接口即可。直接上代码

Java代码  收藏代码
  1. public class RedisCache   implements Cache {  
  2.         private static Log logger = LogFactory.getLog(RedisCache.class);  
  3.         private Jedis redisClient = createClient();  
  4.         /** The ReadWriteLock. */  
  5.         private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();  
  6.           
  7.         private String id;  
  8.         public RedisCache(final String id) {  
  9.                 if (id == null) {  
  10.                         throw new IllegalArgumentException("Cache instances require an ID");  
  11.                 }  
  12.                 logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id=" + id);  
  13.                 this.id = id;  
  14.         }  
  15.   
  16.         @Override  
  17.         public String getId() {  
  18.                 return this.id;  
  19.         }  
  20.   
  21.         @Override  
  22.         public int getSize() {  
  23.                 return Integer.valueOf(redisClient.dbSize().toString());  
  24.         }  
  25.   
  26.         @Override  
  27.         public void putObject(Object key, Object value) {  
  28.                 logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:" + key + "=" + value);  
  29.                 redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));  
  30.         }  
  31.   
  32.         @Override  
  33.         public Object getObject(Object key) {  
  34.                 Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil.serialize(key.toString())));  
  35.                 logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:" + key + "=" + value);  
  36.                 return value;  
  37.         }  
  38.   
  39.         @Override  
  40.         public Object removeObject(Object key) {  
  41.                 return redisClient.expire(SerializeUtil.serialize(key.toString()), 0);  
  42.         }  
  43.   
  44.         @Override  
  45.         public void clear() {  
  46.                 redisClient.flushDB();  
  47.         }  
  48.   
  49.         @Override  
  50.         public ReadWriteLock getReadWriteLock() {  
  51.                 return readWriteLock;  
  52.         }  
  53.          
  54.         protected  static Jedis createClient() {  
  55.                 try {  
  56.                         JedisPool pool = new JedisPool(new JedisPoolConfig(), "172.60.0.172");  
  57.                        return pool.getResource();  
  58.                 } catch (Exception e) {  
  59.                         e.printStackTrace();  
  60.                 }  
  61.                 throw new RuntimeException("初始化连接池错误");  
  62.         }  
  63.           
  64.     
  65.           
  66. }  
  67.   
  68.   
  69. class SerializeUtil {  
  70.         public static byte[] serialize(Object object) {  
  71.                 ObjectOutputStream oos = null;  
  72.                 ByteArrayOutputStream baos = null;  
  73.                 try {  
  74.                         // 序列化  
  75.                         baos = new ByteArrayOutputStream();  
  76.                         oos = new ObjectOutputStream(baos);  
  77.                         oos.writeObject(object);  
  78.                         byte[] bytes = baos.toByteArray();  
  79.                         return bytes;  
  80.                 } catch (Exception e) {  
  81.                         e.printStackTrace();  
  82.                 }  
  83.                 return null;  
  84.         }  
  85.   
  86.         public static Object unserialize(byte[] bytes) {  
  87.                 if(bytes == null)return null;  
  88.                 ByteArrayInputStream bais = null;  
  89.                 try {  
  90.                         // 反序列化  
  91.                         bais = new ByteArrayInputStream(bytes);  
  92.                         ObjectInputStream ois = new ObjectInputStream(bais);  
  93.                         return ois.readObject();  
  94.                 } catch (Exception e) {  
  95.                         e.printStackTrace();  
  96.                 }  
  97.                 return null;  
  98.         }  
  99. }  

 

在看ehcache-mybatis的源码 它真正使用cache的方式是通过集成org.apache.ibatis.cache.decorators.LoggingCache 这个类实现的,照猫画虎,直接我们也继承

Java代码  收藏代码
  1. public class LoggingRedisCache extends LoggingCache {  
  2.   
  3.         public LoggingRedisCache(String id) {  
  4.                 super(new RedisCache(id));  
  5.         }  
  6.         
  7. }  

 

在mapper.xml中添加如下cache标签

 

Xml代码  收藏代码
  1. <!-- 启用缓存 -->  
  2.     <cache type="cn.seafood.cache.LoggingRedisCache" />   

 在mybatis的核心文件中开启缓存

Xml代码  收藏代码
  1. <settings>  
  2.     <!-- 这个配置使全局的映射器启用或禁用缓存 -->  
  3.     <setting name="cacheEnabled" value="true" />  
  4.  <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->      
  5.         <setting name="multipleResultSetsEnabled" value="true"/>  
  6.     <!-- 配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 -->  
  7.     <setting name="defaultExecutorType" value="REUSE" />  
  8.     <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->  
  9.     <setting name="lazyLoadingEnabled" value="false" />  
  10.     <setting name="aggressiveLazyLoading" value="true" />  
  11.     <!-- <setting name="enhancementEnabled" value="true"/> -->  
  12.     <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间。 -->  
  13.     <setting name="defaultStatementTimeout" value="25000" />  
  14. </settings>  

 

<setting name="lazyLoadingEnabled" value="false" />

<setting name="aggressiveLazyLoading" value="true" />

注意着两个属性,需要把属性延迟加载和关联对象加载给关闭了,不然放进redis中的cglib代理对象,在对数据发生更改的时候,会出错。

 

 

在上一篇文中的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. public class RedisCache   implements Cache {  
  28.         private static Log log = LogFactory.getLog(RedisCache.class);  
  29.         /** The ReadWriteLock. */  
  30.         private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();  
  31.           
  32.         private String id;  
  33.         public RedisCache(final String id) {  
  34.                 if (id == null) {  
  35.                         throw new IllegalArgumentException("必须传入ID");  
  36.                 }  
  37.                 log.debug("MybatisRedisCache:id=" + id);  
  38.                 this.id=id;  
  39.         }  
  40.           
  41.         @Override  
  42.         public String getId() {  
  43.                 return this.id;  
  44.         }  
  45.   
  46.         @Override  
  47.         public int getSize() {  
  48.                 Jedis jedis = null;  
  49.                 JedisPool jedisPool = null;  
  50.                 int result = 0;  
  51.                 boolean borrowOrOprSuccess = true;  
  52.                 try {  
  53.                         jedis   = CachePool.getInstance().getJedis();  
  54.                         jedisPool = CachePool.getInstance().getJedisPool();  
  55.                         result = Integer.valueOf(jedis.dbSize().toString());  
  56.                 } catch (JedisConnectionException e) {  
  57.                         borrowOrOprSuccess = false;  
  58.                         if (jedis != null)  
  59.                                 jedisPool.returnBrokenResource(jedis);  
  60.                 } finally {  
  61.                         if (borrowOrOprSuccess)  
  62.                                 jedisPool.returnResource(jedis);  
  63.                 }  
  64.                 return result;  
  65.                    
  66.         }  
  67.   
  68.         @Override  
  69.         public void putObject(Object key, Object value) {  
  70.                 if(log.isDebugEnabled())  
  71.                 log.debug("putObject:" + key.hashCode() + "=" + value);  
  72.                 if(log.isInfoEnabled())  
  73.                 log.info("put to redis sql :" +key.toString());  
  74.                 Jedis jedis = null;  
  75.                 JedisPool jedisPool = null;  
  76.                 boolean borrowOrOprSuccess = true;  
  77.                 try {  
  78.                         jedis   = CachePool.getInstance().getJedis();  
  79.                         jedisPool = CachePool.getInstance().getJedisPool();  
  80.                         jedis.set(SerializeUtil.serialize(key.hashCode()), SerializeUtil.serialize(value));  
  81.                 } catch (JedisConnectionException e) {  
  82.                         borrowOrOprSuccess = false;  
  83.                         if (jedis != null)  
  84.                                 jedisPool.returnBrokenResource(jedis);  
  85.                 } finally {  
  86.                         if (borrowOrOprSuccess)  
  87.                                 jedisPool.returnResource(jedis);  
  88.                 }  
  89.                   
  90.         }  
  91.   
  92.         @Override  
  93.         public Object getObject(Object key) {  
  94.                 Jedis jedis = null;  
  95.                 JedisPool jedisPool = null;  
  96.                 Object value = null;  
  97.                 boolean borrowOrOprSuccess = true;  
  98.                 try {  
  99.                         jedis   = CachePool.getInstance().getJedis();  
  100.                         jedisPool = CachePool.getInstance().getJedisPool();  
  101.                         value  = SerializeUtil.unserialize(jedis.get(SerializeUtil.serialize(key.hashCode())));  
  102.                 } catch (JedisConnectionException e) {  
  103.                         borrowOrOprSuccess = false;  
  104.                         if (jedis != null)  
  105.                                 jedisPool.returnBrokenResource(jedis);  
  106.                 } finally {  
  107.                         if (borrowOrOprSuccess)  
  108.                                 jedisPool.returnResource(jedis);  
  109.                 }  
  110.                 if(log.isDebugEnabled())  
  111.                 log.debug("getObject:" + key.hashCode() + "=" + value);  
  112.                 return value;  
  113.         }  
  114.   
  115.         @Override  
  116.         public Object removeObject(Object key) {  
  117.                 Jedis jedis = null;  
  118.                 JedisPool jedisPool = null;  
  119.                 Object value = null;  
  120.                 boolean borrowOrOprSuccess = true;  
  121.                 try {  
  122.                         jedis   = CachePool.getInstance().getJedis();  
  123.                         jedisPool = CachePool.getInstance().getJedisPool();  
  124.                         value  = jedis.expire(SerializeUtil.serialize(key.hashCode()), 0);  
  125.                 } catch (JedisConnectionException e) {  
  126.                         borrowOrOprSuccess = false;  
  127.                         if (jedis != null)  
  128.                                 jedisPool.returnBrokenResource(jedis);  
  129.                 } finally {  
  130.                         if (borrowOrOprSuccess)  
  131.                                 jedisPool.returnResource(jedis);  
  132.                 }  
  133.                 if(log.isDebugEnabled())  
  134.                 log.debug("getObject:" + key.hashCode() + "=" + value);  
  135.                 return value;  
  136.         }  
  137.   
  138.         @Override  
  139.         public void clear() {  
  140.                 Jedis jedis = null;  
  141.                 JedisPool jedisPool = null;  
  142.                 boolean borrowOrOprSuccess = true;  
  143.                 try {  
  144.                         jedis   = CachePool.getInstance().getJedis();  
  145.                         jedisPool = CachePool.getInstance().getJedisPool();  
  146.                         jedis.flushDB();  
  147.                         jedis.flushAll();  
  148.                 } catch (JedisConnectionException e) {  
  149.                         borrowOrOprSuccess = false;  
  150.                         if (jedis != null)  
  151.                                 jedisPool.returnBrokenResource(jedis);  
  152.                 } finally {  
  153.                         if (borrowOrOprSuccess)  
  154.                                 jedisPool.returnResource(jedis);  
  155.                 }  
  156.         }  
  157.   
  158.         @Override  
  159.         public ReadWriteLock getReadWriteLock() {  
  160.                 return readWriteLock;  
  161.         }  
  162.        /** 
  163.         *  
  164.        * @ClassName: CachePool 
  165.        * @Description: TODO(单例Cache池) 
  166.        * @author LiuYi 
  167.        * @date 2014年6月17日 上午10:50:52 
  168.        * 
  169.         */  
  170.         public static class CachePool {  
  171.                 JedisPool pool;  
  172.                 private static final CachePool cachePool = new CachePool();  
  173.                   
  174.                 public static CachePool getInstance(){  
  175.                         return cachePool;  
  176.                 }  
  177.                 private CachePool() {  
  178.                         JedisPoolConfig config = new JedisPoolConfig();  
  179.                         config.setMaxIdle(100);  
  180.                         config.setMaxWaitMillis(1000l);  
  181.                          PropertiesLoader pl =  new PropertiesLoader("classpath:config/redis.properties");  
  182.                          pool = new JedisPool(config,pl.getProperty("redisvip"));  
  183.                 }  
  184.                 public  Jedis getJedis(){  
  185.                         Jedis jedis = null;  
  186.                         boolean borrowOrOprSuccess = true;  
  187.                         try {  
  188.                                 jedis = pool.getResource();  
  189.                         } catch (JedisConnectionException e) {  
  190.                                 borrowOrOprSuccess = false;  
  191.                                 if (jedis != null)  
  192.                                         pool.returnBrokenResource(jedis);  
  193.                         } finally {  
  194.                                 if (borrowOrOprSuccess)  
  195.                                         pool.returnResource(jedis);  
  196.                         }  
  197.                         jedis = pool.getResource();  
  198.                         return jedis;  
  199.                 }  
  200.                   
  201.                 public JedisPool getJedisPool(){  
  202.                         return this.pool;  
  203.                 }  
  204.                   
  205.         }  
  206.           
  207.           
  208.         public static class SerializeUtil {  
  209.                 public static byte[] serialize(Object object) {  
  210.                         ObjectOutputStream oos = null;  
  211.                         ByteArrayOutputStream baos = null;  
  212.                         try {  
  213.                                 // 序列化  
  214.                                 baos = new ByteArrayOutputStream();  
  215.                                 oos = new ObjectOutputStream(baos);  
  216.                                 oos.writeObject(object);  
  217.                                 byte[] bytes = baos.toByteArray();  
  218.                                 return bytes;  
  219.                         } catch (Exception e) {  
  220.                                 e.printStackTrace();  
  221.                         }  
  222.                         return null;  
  223.                 }  
  224.   
  225.                 public static Object unserialize(byte[] bytes) {  
  226.                         if(bytes == null)return null;  
  227.                         ByteArrayInputStream bais = null;  
  228.                         try {  
  229.                                 // 反序列化  
  230.                                 bais = new ByteArrayInputStream(bytes);  
  231.                                 ObjectInputStream ois = new ObjectInputStream(bais);  
  232.                                 return ois.readObject();  
  233.                         } catch (Exception e) {  
  234.                                 e.printStackTrace();  
  235.                         }  
  236.                         return null;  
  237.                 }  
  238.         }  
  239. }  

 参考链接:http://liuyieyer.iteye.com/blog/2081382

1 0
原创粉丝点击