導入相關依賴java
<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做爲日誌輸出web
日誌咱們使用slf4j,並用log4j來實現。SLF4J不一樣於其餘日誌類庫,與其它有很大的不一樣。redis
SLF4J(Simple logging Facade for Java)不是一個真正的日誌實現,而是一個抽象層( abstraction layer),spring
它容許你在後臺使用任意一個日誌類庫。sql
<!-- 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的配置文件數據庫
<?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>
咱們來測試一下apache
@Test public void cacheSimgle() { Book b1 = this.bookService.selectByPrimaryKey(29); System.out.println(b1); Book b2 = this.bookService.selectByPrimaryKey(29); System.out.println(b2); }
結果:執行了兩次sql語句api
這裏咱們須要在applicationContext-mabatis.xml中加入chache配置緩存
<!--設置mybaits對緩存的支持--> <property name="configurationProperties"> <props> <!-- 全局映射器啓用緩存 *主要將此屬性設置完成便可--> <prop key="cacheEnabled">true</prop> <!-- 查詢時,關閉關聯對象即時加載以提升性能 --> <prop key="lazyLoadingEnabled">false</prop> <!-- 設置關聯對象加載的形態,此處爲按需加載字段(加載字段由SQL指 定),不會加載關聯表的全部字段,以提升性能 --> <prop key="aggressiveLazyLoading">true</prop> </props> </property>
在BookMapper.xml中配置chachemybatis
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
咱們再來測試一下:此次只執行了一次sql語句
測試查詢多個:
@Test public void cacheMany() { Map map =new HashMap(); map.put("bname", StringUtil.toLikeStr("聖墟")); pageBean.setPage(3); List<Map> bbbb = this.bookService.listPager(map,pageBean); for (Map m : bbbb) { System.out.println(m); } List<Map> bbbb2 = this.bookService.listPager(map,pageBean); for (Map m : bbbb2) { System.out.println(m); } }
結果:mabatis二級緩存會默認開啓緩存多條數據
若是不想開啓,咱們能夠經過select標籤的useCache屬性關閉二級緩存
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" useCache="true">
注意有三:
一、mybatis默認使用的二級緩存框架就是ehcache(org.mybatis.caches.ehcache.EhcacheCache),無縫結合
二、Mybatis緩存開關一旦開啓,可緩存單條記錄,也可緩存多條,hibernate不能緩存多條。
三、Mapper接口上的全部方法上另外提供關閉緩存的屬性
添加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>
3.1 添加兩個redis的配置文件,並將redis.properties和applicationContext-redis.xml配置到applicationContext.xml文件中
redis.properties
redis.hostName=192.168.241.132 redis.port=6379 redis.password=123456 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.liuwenwu.util.RedisCacheTransfer"> <property name="redisTemplate" ref="redisTemplate"/> </bean> </beans>
注1:將redis.properties導入到applicationContext.xml文件中
spring中引入第二個屬性文件會出現「找不到某個配置項」錯誤,這是由於spring只容許有一個<context:property-placeholder/>
<!--引入兩個或多個屬性文件的寫法--> <context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties,classpath:redis.properties" />
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"> <!--多文件引用--> <context:property-placeholder location="classpath:jdbc.properties,classpath:redis.properties"/> <!--整合mybatis框架--> <import resource="applicationContext-mabatis.xml"></import> <!--整合redis--> <import resource="applicationContext-redis.xml"></import> </beans>
將redis緩存引入到mybatis中
建立mybatis的自定義緩存類「RedisCache」,必須實現org.apache.ibatis.cache.Cache接口
RedisCache.java
package com.liuwenwu.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);//控制存放時間60s }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」,解決RedisCache中RedisTemplate的靜態注入,從而使MyBatis實現第三方緩存
RedisCacheTransfer.java
package com.liuwenwu.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緩存
<!--配置Redis緩存--> <cache type="com.liuwenwu.util.RedisCache"></cache>
測試查詢單個:
@Test public void cacheSimgle() { Book b1 = this.bookService.selectByPrimaryKey(29); System.out.println(b1); Book b2 = this.bookService.selectByPrimaryKey(29); System.out.println(b2); }
測試查詢多個:
@Test public void cacheMany() { Map map =new HashMap(); map.put("bname", StringUtil.toLikeStr("聖墟")); pageBean.setPage(3); List<Map> bbbb = this.bookService.listPager(map,pageBean); for (Map m : bbbb) { System.out.println(m); } List<Map> bbbb2 = this.bookService.listPager(map,pageBean); for (Map m : bbbb2) { System.out.println(m); } }