ehcache使用_Mybatis整合(Redis、Ehcache)实现二级缓存,恕我直言,你不会
目的:
Mybatis整合ehcache實現二級緩存
- ssm中整合ehcache
在POM中導入相關依賴
org.springframework spring-context-support ${spring.version}org.mybatis.caches mybatis-ehcache 1.1.0net.sf.ehcache ehcache 2.10.0- 修改日志配置,因為ehcache使用了Slf4j作為日志輸出
日志我們使用slf4j,并用log4j來實現。SLF4J不同于其他日志類庫,與其它有很大的不同。
SLF4J(Simple logging Facade for Java)不是一個真正的日志實現,而是一個抽象層( abstraction layer),
它允許你在后臺使用任意一個日志類庫。
Pom.xml
2.9.13.2.01.7.13org.slf4j slf4j-api ${slf4j.version}org.slf4j jcl-over-slf4j ${slf4j.version}runtimeorg.apache.logging.log4j log4j-api ${log4j2.version}org.apache.logging.log4j log4j-core ${log4j2.version}org.apache.logging.log4j log4j-slf4j-impl ${log4j2.version}org.apache.logging.log4j log4j-web ${log4j2.version}runtimecom.lmax disruptor ${log4j2.disruptor.version}在Resource中添加一個ehcache.xml的配置文件
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>在applicationContext-mybatis.xml中給mybatis設置支持
truefalsetrue現在我們來測試一下它訪問是否使用了二級緩存
@Test public void cacheSingle() { Book book= this.bookService.selectByPrimaryKey(5); System.out.println(book); Book book2= this.bookService.selectByPrimaryKey(5); System.out.println(book2); }效果:
很明顯查詢了兩次數據庫,沒有成功,繼續往下看如何解決這個問題
我們需要在BookMapper.xml中加入chache配置
我們在運行之前的測試方法測試一下
很明顯,第一次從數據庫中查詢數據第二次就從緩存中拿數據了
現在我們來測試查詢多條數據的效果
@Test public void cacheMany() { Map map = new HashMap(); map.put("bname", StringUtils.toLikeStr("圣墟")); List hhhh = this.bookService.listPager(map,pageBean); for (Map m : hhhh) { System.out.println(m); } List hhhh2 = this.bookService.listPager(map,pageBean); for (Map m : hhhh2) { System.out.println(m); } }效果:
- 關閉緩存
既然開啟了那就會有關閉緩存的時候,對吧
我們可以通過select標簽的useCache屬性打開或關閉二級緩存即可
注意:
1、mybatis默認使用的二級緩存框架就是ehcache(org.mybatis.caches.ehcache.EhcacheCache),無縫結合
2、Mybatis緩存開關一旦開啟,可緩存單條記錄,也可緩存多條,hibernate不能緩存多條。
3、Mapper接口上的所有方法上另外提供關閉緩存的屬性
Mybatis整合redis實現二級緩存
1. redis常用類
1.1 Jedis
jedis就是集成了redis的一些命令操作,封裝了redis的java客戶端
1.2 JedisPoolConfig
Redis連接池
1.3 ShardedJedis
基于一致性哈希算法實現的分布式Redis集群客戶端
實現 mybatis 的二級緩存,一般來說有如下兩種方式:
1) 采用 mybatis 內置的 cache 機制。
2) 采用三方 cache 框架, 比如ehcache, oscache 等等.
2. 添加jar依賴
添加redis相關依賴
2.9.01.7.1.RELEASEredis.clients jedis ${redis.version}org.springframework.data spring-data-redis ${redis.spring.version}log4j2配置
jackson依賴
2.9.3com.fasterxml.jackson.core jackson-databind ${jackson.version}com.fasterxml.jackson.core jackson-core ${jackson.version}com.fasterxml.jackson.core jackson-annotations ${jackson.version}- spring + redis 集成實現緩存功能(與mybatis無關)
添加兩個redis的配置文件,并將redis.properties和applicationContext-redis.xml配置到applicationContext.xml文件中
redis.properties
redis.hostName=192.168.80.128redis.password=613613redis.timeout=10000redis.maxIdle=300redis.maxTotal=1000redis.maxWaitMillis=1000redis.minEvictableIdleTimeMillis=300000redis.numTestsPerEvictionRun=1024redis.timeBetweenEvictionRunsMillis=30000redis.testOnBorrow=trueredis.testWhileIdle=trueapplicationContext-redis.xml
<?xml version="1.0" encoding="UTF-8"?>將redis.properties導入到applicationContext.xml文件中
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">將redis緩存引入到mybatis中
package com.ht.Util;import org.apache.ibatis.cache.Cache;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.dao.DataAccessException;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.core.RedisCallback;import org.springframework.data.redis.core.RedisTemplate;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;public class RedisCache implements Cache //實現類{ private static final Logger logger = LoggerFactory.getLogger(RedisCache.class); private static RedisTemplate redisTemplate; private final String id; /** * The {@code ReadWriteLock}. */ private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); @Override public ReadWriteLock getReadWriteLock() { return this.readWriteLock; } public static void setRedisTemplate(RedisTemplate redisTemplate) { RedisCache.redisTemplate = redisTemplate; } public RedisCache(final String id) { if (id == null) { throw new IllegalArgumentException("Cache instances require an ID"); } logger.debug("MybatisRedisCache:id=" + id); this.id = id; } @Override public String getId() { return this.id; } @Override public void putObject(Object key, Object value) { try{ logger.info(">>>>>>>>>>>>>>>>>>>>>>>>putObject: key="+key+",value="+value); if(null!=value) redisTemplate.opsForValue().set(key.toString(),value,60, TimeUnit.SECONDS); }catch (Exception e){ e.printStackTrace(); logger.error("redis保存數據異常!"); } } @Override public Object getObject(Object key) { try{ logger.info(">>>>>>>>>>>>>>>>>>>>>>>>getObject: key="+key); if(null!=key) return redisTemplate.opsForValue().get(key.toString()); }catch (Exception e){ e.printStackTrace(); logger.error("redis獲取數據異常!"); } return null; } @Override public Object removeObject(Object key) { try{ if(null!=key) return redisTemplate.expire(key.toString(),1,TimeUnit.DAYS); }catch (Exception e){ e.printStackTrace(); logger.error("redis獲取數據異常!"); } return null; } @Override public void clear() { Long size=redisTemplate.execute(new RedisCallback() { @Override public Long doInRedis(RedisConnection redisConnection) throws DataAccessException { Long size = redisConnection.dbSize(); //連接清除數據 redisConnection.flushDb(); redisConnection.flushAll(); return size; } }); logger.info(">>>>>>>>>>>>>>>>>>>>>>>>clear: 清除了" + size + "個對象"); } @Override public int getSize() { Long size = redisTemplate.execute(new RedisCallback() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.dbSize(); } }); return size.intValue(); }}RedisCacheTransfer
package com.ht.Util;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;public class RedisCacheTransfer { @Autowired public void setRedisTemplate(RedisTemplate redisTemplate) { RedisCache.setRedisTemplate(redisTemplate); }}接下來,我們在BookMapper.xml中配置RedisCache緩存
測試:
@Test public void cacheSingle() { Book book= this.bookService.selectByPrimaryKey(5); System.out.println(book); Book book2= this.bookService.selectByPrimaryKey(5); System.out.println(book2); }總結
以上是生活随笔為你收集整理的ehcache使用_Mybatis整合(Redis、Ehcache)实现二级缓存,恕我直言,你不会的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python爬虫的技能_关于 Pytho
- 下一篇: php 模拟并发请求_PHP模拟并发请求