方法一
(一)、RedisCache(mybatis二级缓存实现类)
/**
* Created by hhjian on 17-6-27.
*/
public class RedisCache implements Cache {
private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);
private static JedisConnectionFactory jedisConnectionFactory;
private final String id;
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public RedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
this.id = id;
}
@Override
public String getId() {
return this.id;
}
@Override
public void putObject(Object o, Object o1) {
RedisConnection connection = jedisConnectionFactory.getConnection();
connection.set(serializer(o), serializer(o1));
connection.close();
}
@Override
public Object getObject(Object key) {
RedisConnection connection = jedisConnectionFactory.getConnection();
Object object = deSerializer(connection.get(serializer(key)));
connection.close();
return object;
}
@Override
public Object removeObject(Object o) {
RedisConnection connection = jedisConnectionFactory.getConnection();
Object object = connection.expire(serializer(o), 0);
return object;
}
@Override
public void clear() {
RedisConnection connection = jedisConnectionFactory.getConnection();
connection.flushDb();
connection.flushAll();
connection.close();
}
@Override
public int getSize() {
RedisConnection connection = jedisConnectionFactory.getConnection();
int size = Integer.valueOf(connection.dbSize().toString());
connection.close();
return size;
}
@Override
public ReadWriteLock getReadWriteLock() {
return this.readWriteLock;
}
public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.jedisConnectionFactory = jedisConnectionFactory;
}
private byte[] serializer(Object arg) {
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
return serializer.serialize(arg);
}
private Object deSerializer(byte[] arg) {
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
return serializer.deserialize(arg);
}
}
(二)、静态注入 jedisConnectionFactory
<bean id="redisCache" class="com.linkworld.dao.RedisCacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
</bean>
/**
* Created by hhjian on 17-6-27.
*/
public class RedisCacheTransfer {
@Autowired
public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
}
}
(三)、开启缓存
<setting name="cacheEnabled" value="true"/>
<cache type="com.linkworld.dao.RedisCache" eviction="FIFO" readOnly="true" />
方法二 官方文档方法
<dependencies>
...
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-redis</artifactId>
<version>1.0.0-beta2</version>
</dependency>
...
</dependencies>
then, just configure it in the mapper XML
<mapper namespace="org.acme.FooMapper">
<cache type="org.mybatis.caches.redis.RedisCache" />
...
</mapper>