背景:java
實際項目中,不少地方須要把數據緩存起來,以加快數據訪問速度。好比字典表,好比數據機房表等等,緩存的實現有不少方式,若是項目中有用到mybatis,能夠使用二級緩存來解決數據的緩存問題。redis
現狀:apache
通常mybatis經過oscache來實現他的二級緩存,然而這種方式存在以下幾個問題:緩存
一、oscache能夠用來緩存頁面和數據對象,但數據一般存放在內存中,項目多實例環境下沒法解決緩存更新和過時的問題。mybatis
二、oscache能夠將數據經過io寫到硬盤保持數據一致性,但此舉會浪費資源app
解決方案:性能
使用redis實現一套mybatis二級緩存插件,將數據從內存轉移到redis中,各個項目訪問惟一一個redis實例(或集羣),這樣就保證在任意時刻,緩存的變化都會被全部項目感知,並使用最新的緩存數據;同時,redis的高性能也保證了緩存數據的高速讀取。spa
實現步驟:插件
目前mybatis社區開放了mybatis-redis項目,能夠從中央倉庫獲取對應依賴。code
pom.xml
<dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-redis</artifactId> <version>1.0.0-beta2</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.0</version> </dependency>
src/redis.properties
blockWhenExhausted=true evictionPolicyClassName=org.apache.commons.pool2.impl.DefaultEvictionPolicy fairness=false host=127.0.0.1 port=6379 jmxEnabled=true jmxNameBase=pool jmxNamePrefix=pool lifo=true maxIdle=8 maxTotal=8 maxWaitMillis=-1 minEvictableIdleTimeMillis=60000 minIdle=0 numTestsPerEvictionRun=-1 softMinEvictableIdleTimeMillis=1800000 testOnBorrow=false testOnCreate=false testOnReturn=false testWhileIdle=true timeBetweenEvictionRunMillis=3000
mapper配置
<mapper namespace="com.voole.p2pauth.system.mappper.IAccessLogMapper"> <cache type="org.mybatis.caches.redis.RedisCache"></cache> <insert id="insertAccessLog" flushCache="true" parameterType="com.voole.p2pauth.system.entry.AccessLogEntry"> INSERT INTO l_access ( Id,…… ) VALUES ( #{id},…… ); </insert> </mapper>