(1)首先是Cache接口定义:

package org.apache.ibatis.cache;import java.util.concurrent.locks.ReadWriteLock;public interface Cache {String getId();int getSize();void putObject(Object key, Object value);Object getObject(Object key);Object removeObject(Object key);void clear();ReadWriteLock getReadWriteLock();}

(2)RedisCache接口实现:

package cn.lsoft.undoner.dao.cache;import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.lsoft.undoner.util.SerializeUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;/** 使用第三方缓存服务器,处理二级缓存*/
public class RedisCache implements Cache {private static Logger logger = LoggerFactory.getLogger(RedisCache.class);/** The ReadWriteLock. */private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();private String id;private JedisPool jedisPool;private static final int DB_INDEX = 1;private final String COMMON_CACHE_KEY = "COM:";private static final String UTF8 = "utf-8";private ApplicationContext context;/*** 按照一定规则标识key*/private String getKey(Object key) {StringBuilder accum = new StringBuilder();accum.append(COMMON_CACHE_KEY);accum.append(this.id).append(":");accum.append(DigestUtils.md5Hex(String.valueOf(key)));return accum.toString();}/*** redis key规则前缀*/private String getKeys() {return COMMON_CACHE_KEY + this.id + ":*";}public RedisCache() {}public RedisCache(final String id) {if (id == null) {throw new IllegalArgumentException("必须传入ID");}context = new ClassPathXmlApplicationContext("/spring/spring-db-redis-context.xml");JedisPoolConfig jedisPoolConfig = (JedisPoolConfig) context.getBean("poolConfig");jedisPool = new JedisPool(jedisPoolConfig, "23.45.6.7", 6379);logger.debug(">>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id=" + id);this.id = id;}@Overridepublic String getId() {return this.id;}@Overridepublic int getSize() {Jedis jedis = null;int result = 0;boolean borrowOrOprSuccess = true;try {jedis = jedisPool.getResource();jedis.select(DB_INDEX);Set<byte[]> keys = jedis.keys(getKeys().getBytes(UTF8));if (null != keys && !keys.isEmpty()) {result = keys.size();}logger.debug(this.id + "---->>>>总缓存数:" + result);} catch (Exception e) {borrowOrOprSuccess = false;if (jedis != null)jedisPool.returnBrokenResource(jedis);} finally {if (borrowOrOprSuccess)jedisPool.returnResource(jedis);}return result;}@Overridepublic void putObject(Object key, Object value) {Jedis jedis = null;boolean borrowOrOprSuccess = true;try {jedis = jedisPool.getResource();jedis.select(DB_INDEX);byte[] keys = getKey(key).getBytes(UTF8);jedis.set(keys, SerializeUtil.serialize(value));logger.debug("添加缓存--------" + this.id + " | " +keys.toString() + ":" + value.toString() );getSize();} catch (Exception e) {borrowOrOprSuccess = false;if (jedis != null)jedisPool.returnBrokenResource(jedis);} finally {if (borrowOrOprSuccess)jedisPool.returnResource(jedis);}}@Overridepublic Object getObject(Object key) {Jedis jedis = null;Object value = null;boolean borrowOrOprSuccess = true;try {jedis = jedisPool.getResource();jedis.select(DB_INDEX);byte[] keys = getKey(key).getBytes(UTF8);value = SerializeUtil.unserialize(jedis.get(getKey(key).getBytes(UTF8)));logger.debug("从缓存中获取-----" + this.id + " | "+keys.toString() + ":"  + value.toString());getSize();} catch (Exception e) {borrowOrOprSuccess = false;if (jedis != null)jedisPool.returnBrokenResource(jedis);} finally {if (borrowOrOprSuccess)jedisPool.returnResource(jedis);}return value;}@Overridepublic Object removeObject(Object key) {Jedis jedis = null;Object value = null;boolean borrowOrOprSuccess = true;try {jedis = jedisPool.getResource();jedis.select(DB_INDEX);byte[] keys = getKey(key).getBytes(UTF8);value = jedis.del(getKey(key).getBytes(UTF8));logger.debug("LRU算法从缓存中移除-----" + this.id + " | " +keys.toString() + ":" + value.toString());getSize();} catch (Exception e) {borrowOrOprSuccess = false;if (jedis != null)jedisPool.returnBrokenResource(jedis);} finally {if (borrowOrOprSuccess)jedisPool.returnResource(jedis);}return value;}@Overridepublic void clear() {Jedis jedis = null;boolean borrowOrOprSuccess = true;try {jedis = jedisPool.getResource();jedis.select(DB_INDEX);// 如果有删除操作,会影响到整个表中的数据,因此要清空一个mapper的缓存(一个mapper的不同数据操作对应不同的key)Set<byte[]> keys = jedis.keys(getKeys().getBytes(UTF8));logger.debug("出现CUD操作,清空对应Mapper缓存======>" + keys.size());for (byte[] key : keys) {jedis.del(key);}// 下面是网上流传的方法,极大的降低系统性能,没起到加入缓存应有的作用,这是不可取的。// jedis.flushDB();// jedis.flushAll();} catch (Exception e) {borrowOrOprSuccess = false;if (jedis != null)jedisPool.returnBrokenResource(jedis);} finally {if (borrowOrOprSuccess)jedisPool.returnResource(jedis);}}@Overridepublic ReadWriteLock getReadWriteLock() {return readWriteLock;}
}

(3)MemcachedCache接口实现:

package org.mybatis.caches.memcached;import java.util.concurrent.locks.ReadWriteLock;import org.apache.ibatis.cache.Cache;/*** The Memcached-based Cache implementation.** @author Simone Tripodi*/
public final class MemcachedCache implements Cache {private static final MemcachedClientWrapper MEMCACHED_CLIENT = new MemcachedClientWrapper();/*** The {@link ReadWriteLock}.*/private final ReadWriteLock readWriteLock = new DummyReadWriteLock();/*** The cache id.*/private final String id;/*** Builds a new Memcached-based Cache.** @param id the Mapper id.*/public MemcachedCache(final String id) {this.id = id;}/*** {@inheritDoc}*/public void clear() {MEMCACHED_CLIENT.removeGroup(this.id);}/*** {@inheritDoc}*/public String getId() {return this.id;}/*** {@inheritDoc}*/public Object getObject(Object key) {return MEMCACHED_CLIENT.getObject(key);}/*** {@inheritDoc}*/public ReadWriteLock getReadWriteLock() {return this.readWriteLock;}/*** {@inheritDoc}*/public int getSize() {return Integer.MAX_VALUE;}/*** {@inheritDoc}*/public void putObject(Object key, Object value) {MEMCACHED_CLIENT.putObject(key, value, this.id);}/*** {@inheritDoc}*/public Object removeObject(Object key) {return MEMCACHED_CLIENT.removeObject(key);}}

(3)EhcacheCache接口实现:

package org.mybatis.caches.ehcache;import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.CacheException;/*** Cache adapter for Ehcache.** @version $Id: EhcacheCache.java 3454 2010-12-29 20:35:44Z simone.tripodi $*/
public final class EhcacheCache implements Cache {/*** The cache manager reference.*/private static final CacheManager CACHE_MANAGER = createCacheManager();/*** Looks for "/ehcache.xml" classpath resource and builds the relative* {@code CacheManager}; if it's no found or it is impossible to load it,* returns the default manager.** @return the application cache manager.*/private static CacheManager createCacheManager() {CacheManager cacheManager;InputStream input = EhcacheCache.class.getResourceAsStream("/ehcache.xml");if (input != null) {try {cacheManager = CacheManager.create(input);} catch (Throwable t) {cacheManager = CacheManager.create();} finally {try {input.close();} catch (IOException e) {}}} else {cacheManager = CacheManager.create();}return cacheManager;}/*** The {@code ReadWriteLock}.*/private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();/*** The cache id.*/private final String id;/***** @param id*/public EhcacheCache(final String id) {if (id == null) {throw new IllegalArgumentException("Cache instances require an ID");}this.id = id;if (!CACHE_MANAGER.cacheExists(this.id)) {CACHE_MANAGER.addCache(this.id);}}/*** {@inheritDoc}*/public void clear() {this.getCache().removeAll();}/*** {@inheritDoc}*/public String getId() {return this.id;}/*** {@inheritDoc}*/public Object getObject(Object key) {try {Element cachedElement = this.getCache().get(key.hashCode());if (cachedElement == null) {return null;}return cachedElement.getObjectValue();} catch (Throwable t) {throw new CacheException(t);}}/*** {@inheritDoc}*/public ReadWriteLock getReadWriteLock() {return this.readWriteLock;}/*** {@inheritDoc}*/public int getSize() {try {return this.getCache().getSize();} catch (Throwable t) {throw new CacheException(t);}}/*** {@inheritDoc}*/public void putObject(Object key, Object value) {try {this.getCache().put(new Element(key.hashCode(), value));} catch (Throwable t) {throw new CacheException(t);}}/*** {@inheritDoc}*/public Object removeObject(Object key) {try {Object obj = this.getObject(key);this.getCache().remove(key.hashCode());return obj;} catch (Throwable t) {throw new CacheException(t);}}/*** Returns the ehcache manager for this cache.** @return the ehcache manager for this cache.*/private Ehcache getCache() {return CACHE_MANAGER.getCache(this.id);}/*** {@inheritDoc}*/@Overridepublic boolean equals(Object obj) {if (this == obj) {return true;}if (obj == null) {return false;}if (!(obj instanceof Cache)) {return false;}Cache otherCache = (Cache) obj;return this.id.equals(otherCache.getId());}/*** {@inheritDoc}*/@Overridepublic int hashCode() {return this.id.hashCode();}/*** {@inheritDoc}*/@Overridepublic String toString() {return "EHCache {"+ this.id+ "}";}}

ibatis.cache接口实现:RedisCache,MemcachedCache,EhcacheCache相关推荐

  1. mysql ehcache_MyBatis使用Ehcache作为二级缓存

    特别说明:由于二级缓存是基于Mapper的,当你在不同的mapper中查询了相同的数据,例如不同的Mapper中有多表查询时结果中有相同的数据,当其中一个Mapper进行插入更新缓存时,另一个并没有插 ...

  2. Spring Cache 实战:兼容所有缓存中间件!

    作者 | 悟空聊架构 来源 | 悟空聊架构(ID:PassJava666) 本篇给大家介绍一种兼容所有缓存中间件的方案,不论我们是使用 Redis 还是 Ehcache,都不需要关心如何操作 Redi ...

  3. SpringBoot2.0 基础案例(13):基于Cache注解模式,管理Redis缓存

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.Cache缓存简介 从Spring3开始定义Cache和Cac ...

  4. Spring Boot : Cache相关简介

    1.美图 2.概述 首先了解一下:java : JSR107缓存规范 Spring缓存抽象 Spring从3.1开始定义了org.springframework.cache.Cache和org.spr ...

  5. ssm+redis整合(通过cache方式)

    这几天的研究ssm redis 终于进入主题了,今天参考了网上一些文章搭建了一下ssm+redis整合,特别记录下来以便以后可以查询使用,有什么不足请大牛们提点 项目架构 1.pom.xml < ...

  6. tair整合Spring Cache

    Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口来统一不同的缓存技术:并支 ...

  7. 带你彻底搞懂MyBatis的底层实现之缓存模块(Cache)-吊打面试官必备技能

      基础支持层位于MyBatis整体架构的最底层,支撑着MyBatis的核心处理层,是整个框架的基石.基础支持层中封装了多个较为通用的.独立的模块.不仅仅为MyBatis提供基础支撑,也可以在合适的场 ...

  8. Spring Cache 缓存原理与 Redis 实践

    说到Spring Boot缓存,那就不得不提JSR-107规范,它告诉我们在Java中如何规范地使用缓存. JSR是Java Specification Requests的简称,通常译为"J ...

  9. 缓存初解(四)---Ibatis的缓存配置+Ehcache

    项目完结,整理一些技术方面的相关收获. 已经记不得EhCacheController这个实现类最早来自于那里了,总之稍加修改后非常有效果,大家就这么用了,感谢最初开源的那位兄弟.这里,主要是做个记录, ...

最新文章

  1. vscode 新建php模板,使用VSCode快速创建vue文件模版的方法介绍
  2. [FJOI2016]建筑师(斯特林数)
  3. redis desktop manager download
  4. 最渣的 Spring Boot 文章
  5. “约见”面试官系列之常见面试题之第一百零一篇之vue-router传参(建议收藏)
  6. MLE(最大似然估计)和EM算法
  7. dede织梦调用顶级二级栏目及下三级栏目方法!
  8. TCP半连接队列(syns queue)和全连接队列(accept queue)
  9. Apache Commons介绍(转载)
  10. 无所不在的性能测试——《LoadRunner 没有告诉你的》之五
  11. android 文件下载和保存
  12. arcgis利用切片服务导出离线地图包(tpk文件)
  13. 双精度,单精度和半精度
  14. PC机装Openwrt19.07做BT下载机的详细配置
  15. Android结课大作业报告
  16. 树莓派基础实验12:PCF8591模数转换器实验
  17. 微信小程序开发百度云分享
  18. 社交网络中的Link Prediction
  19. mac机c4d更改语言,Win/Mac版:C4D R18 三维软件 Cinema 4D C4D R18 正式完整版 + 中文/英文注册机版...
  20. 【转】微信公众号h5网页被嵌入广告 不知道什么原因

热门文章

  1. radware负载均衡器配置adc
  2. 【Total Commander】 在快速搜索的时候只显示满足条件的文件
  3. mysql 全连接_MySQL全连接(Full Join)实现,union和union all用法
  4. 如何低成本快速获取种子用户
  5. Python机器学习:corr()探索自变量与因变量的相关性
  6. 医疗人员计算机职称考试题库,全国计算机职称考试题库.pdf
  7. 动态可缓存的内容管理系统(CMS)
  8. Java中文jsp页面被转码了_JSP中文乱码问题终极解决方案
  9. BAT脚本编写教程简单入门篇
  10. 网站实现QQ第三方登录详细步骤