之前SpringMvc和mybatis整合的例子:http://www.cnblogs.com/acehalo/p/3901809.html
為mybatis添加ehcache緩存,參考的http://www.verydemo.com/demo_c180_i57073.html
pom添加:
<!-- ehchache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.8.3</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.0.0</version> </dependency>
之后新建ehcache.xml,放在classpath下,就是和applicationContext.xml同級目錄下:
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../bin/ehcache.xsd"> <defaultCache overflowToDisk="true" eternal="false" maxElementsInMemory="1" /> <diskStore path="S:/cache" /> </ehcache>
之后再mapper下添加:
<mapper namespace="com.hi.test.mapper.UserMapper">下面添加:
<!-- <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/> //最普通的設置,沿用全局設置 --> <cache type="org.mybatis.caches.ehcache.LoggingEhcache" > <property name="timeToIdleSeconds" value="3600"/><!--1 hour--> <property name="timeToLiveSeconds" value="3600"/><!--1 hour--> <property name="maxEntriesLocalHeap" value="1000"/> <property name="maxEntriesLocalDisk" value="10000000"/> <property name="memoryStoreEvictionPolicy" value="LRU"/> </cache> <!-- 配置這個mapper使用LRU替換策略。 (個人比較贊同這種配置,因為每個表的數據都不一樣,有一些需要經常更新,有得可能某幾個字段需要經常做連接, 使用一樣的cache不太合適) -->
這樣就添加完了,之后看下效果:
首先把TxTestService類下的throw new RuntimeException();注釋掉,因為現在需要進行批量插入數據。
打開http://localhost:8080/Test/druid/sql.html這個界面看sql查詢
然后打開http://localhost:8080/Test/TxTest.do 進行插入數據
之后能在druid的監控頁面看到執行了100次insert。
然后打開http://localhost:8080/Test/indexList.do
之后能在druid的監控頁面看到執行了1次select。
之后關閉瀏覽器,或者新開小號窗口,隱私窗口之類的再次訪問
http://localhost:8080/Test/indexList.do
發現在druid的監控界面依然只有1次select。
再打開http://localhost:8080/Test/TxTest.do 進行插入數據。
druid監控的insert變為200次。
訪問http://localhost:8080/Test/indexList.do
之后看druid可以發現再次執行了1次select,總共select變為了2次
再打開http://localhost:8080/Test/indexList.do
select次數依舊是2次。
這樣應該就能說明緩存正常開啟了。
現在還有個問題,暫時還沒解決,緩存臟讀取的問題:
如果我在另一個mapper對user表進行插入操作:即 新建一個bean取名UserNew,一個Mapper取名UserNewMapper,一個UserNewMapper.xml,
如果我利用這個新的對象對user表進行操作。
那么此時原來的UserMapper依舊是讀取緩存的數據,無法讀取實時的數據。
繼而想到,表操作很多都是關聯操作,這樣的緩存肯定存在一定問題,
尋求解決方案中。
又試了下:
不知道為什么,感覺mapper里的cache配置沒有用
<property name="timeToLiveSeconds" value="3600"/> 把value設置成10 也不起作用
加上<property name="eternal" value="false"/>也不起作用
最后把mapper里的cache配置刪了
只留下:
<cache type="org.mybatis.caches.ehcache.LoggingEhcache" > </cache>
即把配置放到ehcache.xml中:
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../bin/ehcache.xsd"> <defaultCache overflowToDisk="true" eternal="false" maxElementsInMemory="1" timeToLiveSeconds="10" maxEntriesLocalHeap="1000" maxEntriesLocalDisk="10000000" memoryStoreEvictionPolicy="LRU" /> <diskStore path="S:/cache" /> </ehcache>
這樣timeToLiveSeconds就起作用了。
10秒刷新。
暫時覺得就先這樣解決緩存臟讀取的問題吧