本次介绍一下使用mybatis-redis项目作为mybatis的二级缓存在生产项目中的配置与应用。
首先,在pom中添加一下依赖:
<!-- mybatis cache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-redis</artifactId>
<version>1.0.0-beta2</version>
</dependency>
依赖添加成功后,在src/main/resources下面创建redis的配置文件redis.properties
#1.0 redis factory configuration
host=xxx.xxx.xxx.xxx
port=6379
password=xxxxxxxx
timeout=5000
usePool=true
#redis pool configuration
maxTotal=600
maxIdle=300
minIdle=10
maxWaitMillis=2000
testOnBorrow=false
testOnReturn=false
配置文件创建成功后,在生成的 xxxMapper.xml中写入配置在<mapper></mapper>之间
<cache type="org.mybatis.caches.redis.RedisCache" />

useCache表示是否需要使用缓存
flushCache表示插入后是否需要刷新缓存
<select ... flushCache="false" useCache="true"/>
<insert ... flushCache="true"/>
<update ... flushCache="true"/>
<delete ... flushCache="true"/>
测试代码如下,update后同步刷新缓存,采用默认配置即可。
@Test
public void test01() {
Vc3JourneyAttributeDefinitions vc3JourneyAttributeDefinitions=new Vc3JourneyAttributeDefinitions();
vc3JourneyAttributeDefinitions=vc3JourneyAttributeDefinitionsMapper.selectByPrimaryKey(1L);
vc3JourneyAttributeDefinitions.setAttributeName("Total distance of valid pulses");
vc3JourneyAttributeDefinitionsMapper.updateByPrimaryKey(vc3JourneyAttributeDefinitions);
vc3JourneyAttributeDefinitions=vc3JourneyAttributeDefinitionsMapper.selectByPrimaryKey(1L);
System.out.println(vc3JourneyAttributeDefinitions.getAttributeName());
}
从github上面https://github.com/mybatis/redis-cache
可以下载源码查看。