Mybatis的缓存,可以分为一级缓存与二级缓存。一级缓存以一次sqlSession为单位,保存查找的信息。每次有更新操作的时候,例如删除,添加,修改等这些操作,缓存区都会刷新。二级缓存以一个或者多个namespace为单位,保存信息。一个简述,不再细讲。
Mybatis提供了一个Cache接口,在我们要实现自己的缓存机制时,需要自己去实现这个接口。
Cache接口与方法:
下面是源码,方法都是见名析义的,自个加了些注释。
public interface Cache {
/**
* @return The identifier of this cache
*/
String getId();//返回ID,顾名思义,在自己实现接口时,也要定义一个ID属性,并且返回。
/**
* @param key Can be any object but usually it is a {@link CacheKey}
* @param value The result of a select.
*/
/**
设置key-value,就是通过键值对的方式缓存数据,mybatis的一级缓存也是通过Map这样实现的。
*/
void putObject(Object key, Object value);
/**
* @param key The key
* @return The object stored in the cache.
*/
/**
根据key查找value
*/
Object getObject(Object key);
/**
* As of 3.3.0 this method is only called during a rollback
* for any previous value that was missing in the cache.
* This lets any blocking cache to release the lock that
* may have previously put on the key.
* A blocking cache puts a lock when a value is null
* and releases it when the value is back again.
* This way other threads will wait for the value to be
* available instead of hitting the database.
*
*
* @param key The key
* @return Not used
*/
/**
按照key移除value
*/
Object removeObject(Object key);
/**
* Clears this cache instance
* 清除整个缓存空间。
*/
void clear();
/**
* Optional. This method is not called by the core.
* 返回缓存的数目
* @return The number of elements stored in the cache (not its capacity).
*/
int getSize();
/**
* Optional. As of 3.2.6 this method is no longer called by the core.
*
* Any locking needed by the cache must be provided internally by the cache provider.
* 可重入读写锁制
* @return A ReadWriteLock
*/
ReadWriteLock getReadWriteLock();
}
基本是这样子,其中,有几个方法一定要有具体的实现。分别是
储值,取值,按key移除,整个清空四个方法。另外,还要实现一个带有ID参数的构造器,否则会抛异常。
怎么使用jedis,网上有很多,就不再说了。自己写的代码如下:
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.exceptions.JedisConnectionException;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 测试,Mybatis采用Redis作为二级缓存
*/
public class RedisCacheTest implements Cache {
/**
* logger
*/
private static Logger logger = LoggerFactory.getLogger(RedisCacheTest.class);
private String id;
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private static JedisConnectionFactory jedisConnectionFactory;
private static String expire;
public RedisCacheTest() {}
public RedisCacheTest(String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
this.id = id;
}
public String getId() {
return id;
}
public void putObject(Object key, Object value) {
JedisConnection jedisConnection = null;
jedisConnectionFactory.afterPropertiesSet();
try {
jedisConnection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
jedisConnection.set(serializer.serialize(key), serializer.serialize(value));
jedisConnection.expire(serializer.serialize(key),Integer.valueOf(expire));//设置此次key的失效时间
} catch (JedisConnectionException e) {
e.printStackTrace();
logger.error( e.getMessage());
} finally {
if (jedisConnection != null) {
jedisConnection.close();
}
}
}
public Object getObject(Object key) {
JedisConnection jedisConnection = null;
jedisConnectionFactory.afterPropertiesSet();
byte[] result;
Object res = null;
try {
jedisConnection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
result = jedisConnection.get(serializer.serialize(key));
res = serializer.deserialize(result);
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (jedisConnection != null) {
jedisConnection.close();
}
}
return res;
}
public Object removeObject(Object key) {
jedisConnectionFactory.afterPropertiesSet();
JedisConnection connection = null;
Object result = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
result = connection.expire(serializer.serialize(key), 0);
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
}
return result;
}
public void clear() {
JedisConnection jedisConnection = null;
jedisConnectionFactory.afterPropertiesSet();
try {
jedisConnection = jedisConnectionFactory.getConnection(); //连接清除数据
jedisConnection.flushDb();
jedisConnection.flushAll();
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (jedisConnection != null) {
jedisConnection.close();
}
}
}
public int getSize() {
jedisConnectionFactory.afterPropertiesSet();
int result = 0;
JedisConnection jedisConnection = null;
try {
jedisConnection = jedisConnectionFactory.getConnection();
result = Integer.valueOf(jedisConnection.dbSize().toString());
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (jedisConnection != null) {
jedisConnection.close();
}
}
return result;
}
public ReadWriteLock getReadWriteLock() {
return this.readWriteLock;
}
public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCacheTest.jedisConnectionFactory = jedisConnectionFactory;
}
public static void setExpires(String expire){
RedisCacheTest.expire = expire;
}
}
****依赖****
==========
关于Mybatis的依赖就不说了,关于redis的依赖主要有以下几个,这些依赖最好不要用最新的正式版,而是用前几个版本的,否则出了错不好找答案。当然,大神忽视。
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.pool</artifactId>
<version>1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.5.0</version>
</dependency>
**xml配置**
---------
xml配置主要就是mybatis的mapper文件的设置,一个spring整合mybatis的xml配置。网上有很多,照着用就好了。
**spring-redis的配置主要片段如下**
<!-- redis数据源 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="testOnBorrow" >
<value type="java.lang.Boolean">false</value>
</property>
</bean>
<!-- Spring-redis连接池管理工厂 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="127.0.0.1" />
<property name="port">
<value type="java.lang.Integer" >6379</value>
</property>
<property name="password" value="" />
<property name="timeout">
<value type="java.lang.Integer" >10000</value>
</property>
<property name="poolConfig" ref="poolConfig" />
</bean>
mapper文件里要新写一个标签,<catch />标签,这个标签主要有四个属性。
给一下官方解释的地址,
> http://www.mybatis.org/mybatis-3/sqlmap-xml.html#cache。
有四个属性,大概解释一下:
type:要使用的缓存类,可以用官方默认的,自己实现了之后,就要换成自己的二级缓存实现类;
flushInterval:缓存的刷新周期,要配合下面select标签的flushCache属性使用;
size:缓存的数量,默认就是1024;
eviction:缓存的刷新策略;有四种,FIFO,先入先出,LRU,最少使用的移除,SOFT与WEAK;
============================
****mybatis的配置文件,要开启二级缓存的配置:****
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 全局映射器启用缓存 *主要将此属性设置完成即可-->
<setting name="cacheEnabled" value="true"/>
<!-- 查询时,关闭关联对象即时加载以提高性能 -->
<setting name="lazyLoadingEnabled" value="false"/>
<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
<setting name="multipleResultSetsEnabled" value="true"/>
<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
<setting name="aggressiveLazyLoading" value="true"/>
</settings>
“`
大体上spring里面用redis作mybatis的二级缓存就是这样了。有一个刷新的问题,cache标签设置了flushInterval属性后并没有起到作用,最后是通过设置redis的key失效时间,间接实现的。