背景: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>