目的:
Mybatis整合ehcache實現二級緩存
- ssm中整合ehcache
在POM中導入相關依賴
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <!--mybatis與ehcache整合--> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.1.0</version> </dependency> <!--ehcache依賴--> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.0</version> </dependency>
- 修改日志配置,因為ehcache使用了Slf4j作為日志輸出
日志我們使用slf4j,並用log4j來實現。SLF4J不同於其他日志類庫,與其它有很大的不同。
SLF4J(Simple logging Facade for Java)不是一個真正的日志實現,而是一個抽象層( abstraction layer),
它允許你在后台使用任意一個日志類庫。
Pom.xml
<!-- log4j2日志配置相關依賴 --> <log4j2.version>2.9.1</log4j2.version> <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version> <slf4j.version>1.7.13</slf4j.version> <!-- log4j2日志相關依賴 --> <!-- log配置:Log4j2 + Slf4j --> <!-- slf4j核心包--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <!--核心log4j2jar包--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j2.version}</version> </dependency> <!--用於與slf4j保持橋接--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j2.version}</version> </dependency> <!--web工程需要包含log4j-web,非web工程不需要--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>${log4j2.version}</version> <scope>runtime</scope> </dependency> <!--需要使用log4j2的AsyncLogger需要包含disruptor--> <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>${log4j2.disruptor.version}</version> </dependency>
在Resource中添加一個ehcache.xml的配置文件
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"> <!--磁盤存儲:將緩存中暫時不使用的對象,轉移到硬盤,類似於Windows系統的虛擬內存--> <!--path:指定在硬盤上存儲對象的路徑--> <!--java.io.tmpdir 是默認的臨時文件路徑。 可以通過如下方式打印出具體的文件路徑 System.out.println(System.getProperty("java.io.tmpdir"));--> <diskStore path="java.io.tmpdir"/> <!--defaultCache:默認的管理策略--> <!--eternal:設定緩存的elements是否永遠不過期。如果為true,則緩存的數據始終有效,如果為false那么還要根據timeToIdleSeconds,timeToLiveSeconds判斷--> <!--maxElementsInMemory:在內存中緩存的element的最大數目--> <!--overflowToDisk:如果內存中數據超過內存限制,是否要緩存到磁盤上--> <!--diskPersistent:是否在磁盤上持久化。指重啟jvm后,數據是否有效。默認為false--> <!--timeToIdleSeconds:對象空閑時間(單位:秒),指對象在多長時間沒有被訪問就會失效。只對eternal為false的有效。默認值0,表示一直可以訪問--> <!--timeToLiveSeconds:對象存活時間(單位:秒),指對象從創建到失效所需要的時間。只對eternal為false的有效。默認值0,表示一直可以訪問--> <!--memoryStoreEvictionPolicy:緩存的3 種清空策略--> <!--FIFO:first in first out (先進先出)--> <!--LFU:Less Frequently Used (最少使用).意思是一直以來最少被使用的。緩存的元素有一個hit 屬性,hit 值最小的將會被清出緩存--> <!--LRU:Least Recently Used(最近最少使用). (ehcache 默認值).緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那么現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存--> <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/> <!--name: Cache的名稱,必須是唯一的(ehcache會把這個cache放到HashMap里)--> <cache name="stuCache" eternal="false" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/> </ehcache>
在applicationContext-mybatis.xml中給mybatis設置支持
<!--設置mybaits對緩存的支持--> <property name="configurationProperties"> <props> <!-- 全局映射器啟用緩存 *主要將此屬性設置完成即可--> <prop key="cacheEnabled">true</prop> <!-- 查詢時,關閉關聯對象即時加載以提高性能 --> <prop key="lazyLoadingEnabled">false</prop> <!-- 設置關聯對象加載的形態,此處為按需加載字段(加載字段由SQL指 定),不會加載關聯表的所有字段,以提高性能 --> <prop key="aggressiveLazyLoading">true</prop> </props> </property>
現在我們來測試一下它訪問是否使用了二級緩存
@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配置
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
我們在運行之前的測試方法測試一下
很明顯,第一次從數據庫中查詢數據第二次就從緩存中拿數據了
現在我們來測試查詢多條數據的效果
@Test public void cacheMany() { Map map = new HashMap(); map.put("bname", StringUtils.toLikeStr("聖墟")); List<Map> hhhh = this.bookService.listPager(map,pageBean); for (Map m : hhhh) { System.out.println(m); } List<Map> hhhh2 = this.bookService.listPager(map,pageBean); for (Map m : hhhh2) { System.out.println(m); } }
效果:
-
關閉緩存
既然開啟了那就會有關閉緩存的時候,對吧
我們可以通過select標簽的useCache屬性打開或關閉二級緩存即可
<select id="selectByPrimaryKey" resultType="com.ht.model.Book" useCache="false"><select/>
注意:
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相關依賴
<!-- redis與spring的整合依賴 --> <redis.version>2.9.0</redis.version> <redis.spring.version>1.7.1.RELEASE</redis.spring.version> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${redis.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${redis.spring.version}</version> </dependency>
log4j2配置
jackson依賴
<!-- jackson --> <jackson.version>2.9.3</jackson.version> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency>
-
spring + redis 集成實現緩存功能(與mybatis無關)
添加兩個redis的配置文件,並將redis.properties和applicationContext-redis.xml配置到applicationContext.xml文件中
redis.properties
redis.hostName=192.168.80.128 redis.password=613613 redis.timeout=10000 redis.maxIdle=300 redis.maxTotal=1000 redis.maxWaitMillis=1000 redis.minEvictableIdleTimeMillis=300000 redis.numTestsPerEvictionRun=1024 redis.timeBetweenEvictionRunsMillis=30000 redis.testOnBorrow=true redis.testWhileIdle=true
applicationContext-redis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 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"> <!-- 1. 引入properties配置文件 --> <!--<context:property-placeholder location="classpath:redis.properties" />--> <!-- 2. redis連接池配置--> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!--最大空閑數--> <property name="maxIdle" value="${redis.maxIdle}"/> <!--連接池的最大數據庫連接數 --> <property name="maxTotal" value="${redis.maxTotal}"/> <!--最大建立連接等待時間--> <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/> <!--逐出連接的最小空閑時間 默認1800000毫秒(30分鍾)--> <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/> <!--每次逐出檢查時 逐出的最大數目 如果為負數就是 : 1/abs(n), 默認3--> <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/> <!--逐出掃描的時間間隔(毫秒) 如果為負數,則不運行逐出線程, 默認-1--> <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/> <!--是否在從池中取出連接前進行檢驗,如果檢驗失敗,則從池中去除連接並嘗試取出另一個--> <property name="testOnBorrow" value="${redis.testOnBorrow}"/> <!--在空閑時檢查有效性, 默認false --> <property name="testWhileIdle" value="${redis.testWhileIdle}"/> </bean> <!-- 3. redis連接工廠 --> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <property name="poolConfig" ref="poolConfig"/> <!--IP地址 --> <property name="hostName" value="${redis.hostName}"/> <!--端口號 --> <property name="port" value="${redis.port}"/> <!--如果Redis設置有密碼 --> <property name="password" value="${redis.password}"/> <!--客戶端超時時間單位是毫秒 --> <property name="timeout" value="${redis.timeout}"/> </bean> <!-- 4. redis操作模板,使用該對象可以操作redis --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="connectionFactory"/> <!--如果不配置Serializer,那么存儲的時候缺省使用String,如果用User類型存儲,那么會提示錯誤User can't cast to String!! --> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/> </property> <!--開啟事務 --> <property name="enableTransactionSupport" value="true"/> </bean> <!-- 5.使用中間類解決RedisCache.RedisTemplate的靜態注入,從而使MyBatis實現第三方緩存 --> <bean id="redisCacheTransfer" class="com.ht.Util.RedisCacheTransfer"> <property name="redisTemplate" ref="redisTemplate"/> </bean> </beans>
將redis.properties導入到applicationContext.xml文件中
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
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"> <!--引入兩個或多個屬性文件的寫法-->
<!--pring中引入第二個屬性文件會出現“找不到某個配置項”錯誤,這是因為spring只允許有一個<context:property-placeholder/>-->
<context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties,classpath:redis.properties" /> <!--整合mybatis框架--> <import resource="applicationContext-mybatis.xml"></import> <!--整合redis框架--> <import resource="applicationContext-redis.xml"></import> </beans>
將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<String,Object> 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<Long>() { @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<Long>() { @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緩存
<cache type="com.ht.Util.RedisCache"></cache>
測試:
@Test public void cacheSingle() { Book book= this.bookService.selectByPrimaryKey(5); System.out.println(book); Book book2= this.bookService.selectByPrimaryKey(5); System.out.println(book2); }
謝謝觀看!