背景:
实际项目中,很多地方需要把数据缓存起来,以加快数据访问速度。比如字典表,比如数据机房表等等,缓存的实现有很多方式,如果项目中有用到mybatis,可以使用二级缓存来解决数据的缓存问题。
现状:
一般mybatis通过oscache来实现他的二级缓存,然而这种方式存在如下几个问题:
1、oscache可以用来缓存页面和数据对象,但数据通常存放在内存中,项目多实例环境下无法解决缓存更新和过期的问题。
2、oscache可以将数据通过io写到硬盘保持数据一致性,但此举会浪费资源
解决方案:
使用redis实现一套mybatis二级缓存插件,将数据从内存转移到redis中,各个项目访问唯一一个redis实例(或集群),这样就保证在任意时刻,缓存的变化都会被所有项目感知,并使用最新的缓存数据;同时,redis的高性能也保证了缓存数据的高速读取。
实现步骤:
目前mybatis社区开放了mybatis-redis项目,可以从中央仓库获取对应依赖。
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>