MyBatisEhcache二级缓存的开启
生活随笔
收集整理的這篇文章主要介紹了
MyBatisEhcache二级缓存的开启
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
mybatis二級緩存對細粒度的數據級別的緩存實現不好,比如如下需求:對商品信息進行緩存,由于商品信息查詢訪問量大,但是要求用戶每次都能查詢最新的商品信息,
???????????此時如果使用mybatis的二級緩存就無法實現當一個商品變化時只刷新該商品的緩存信息而不刷新其它商品的信息,因為mybaits的二級緩存區域以mapper為單位劃分,
???????????當一個商品信息變化會將所有商品信息的緩存數據全部清空。解決此類問題需要在業務層根據需求對數據有針對性緩存。
???? 緩存都是實現了Cache這個接口.....
?
如何開啟 二級緩存,步驟如下:
?? ??? ?1.導入ehcache相關jar包 ?(ehcache: 緩存插件,插件:就是對現有應用軟件功能的一個擴展)?? ??? ?
???2,開啟mybatis的二級緩存?
在mybatis核心配置文件mybatis-config.xml中加入<settings><!-- 開啟二級緩存 --><setting name="cacheEnabled" value="true" /></settings> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mybatis.dao.EmployeeMapper"><cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache> </mapper>?
3.在classpath下加入ehcache.xml文件
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"><diskStore path="java.io.tmpdir"/><defaultCachemaxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true"maxElementsOnDisk="10000000"diskPersistent="false"diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU"/><!--默認緩存配置,以下屬性是必須的:name :cache的標識符,在一個CacheManager中必須唯一。maxElementsInMemory : 在內存中緩存的element的最大數目。maxElementsOnDisk : 在磁盤上緩存的element的最大數目。eternal : 設定緩存的elements是否有有效期。如果為true,timeouts屬性被忽略。overflowToDisk : 設定當內存緩存溢出的時候是否將過期的element緩存到磁盤上。以下屬性是可選的:timeToIdleSeconds : 緩存element在過期前的空閑時間。timeToLiveSeconds : 緩存element的有效生命期。diskPersistent : 在VM重啟的時候是否持久化磁盤緩存,默認是false。diskExpiryThreadIntervalSeconds : 磁盤緩存的清理線程運行間隔,默認是120秒.memoryStoreEvictionPolicy : 當內存緩存達到最大,有新的element加入的時候,移除緩存中element的策略。默認是LRU,可選的有LFU和FIFO--> </ehcache>測試整合ehcache的二級緩存
SqlSession openSession = sqlSessionFactory.openSession(); SqlSession openSession2 = sqlSessionFactory.openSession();try {DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);DepartmentMapper mapper2 = openSession2.getMapper(DepartmentMapper.class);Department departmentById = mapper.getDepartmentById(1);System.out.println(departmentById);openSession.close();Department departmentById2 = mapper2.getDepartmentById(1);System.out.println(departmentById2);} catch (Exception e) {e.printStackTrace(); }finally {openSession2.close(); }?
?
?
?
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的MyBatisEhcache二级缓存的开启的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MyBatis二级缓存的关闭
- 下一篇: MyBatis使增删改不刷新二级缓存