Springmvc整合Redis做MyBatis二级缓存
pom引包
这里使用的是spring-data-redis 2.0以上版本
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-keyvalue</artifactId>
<version>2.1.0.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
redis配置
redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath*:/redis.properties" ignore-unresolvable="true"/>
<!--设置数据池-->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="minIdle" value="${redis.minIdle}"/>
<property name="maxTotal" value="${redis.maxTotal}"/>
<property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
</bean>
<!--redis链接密码-->
<bean id="redisPassword" class="org.springframework.data.redis.connection.RedisPassword">
<constructor-arg name="thePassword" value="${redis.password}"></constructor-arg>
</bean>
<!--链接redis-->
<bean id="redisStandaloneConfiguration" class="org.springframework.data.redis.connection.RedisStandaloneConfiguration">
<property name="hostName" value="${redis.host}"/>
<property name="port" value="${redis.port}"/>
<property name="password" ref="redisPassword"/>
<!-- <property name="usePool" value="${redis.usePool}"/>
<property name="timeout" value="${redis.timeout}"/>
<property name="poolConfig" ref="jedisPoolConfig"/> -->
<property name="database" value="${redis.dbIndex}"/>
</bean>
<!-- Redis Sentine 哨兵集群配置 -->
<bean id="redisSentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
<constructor-arg index="0" value="${redis.master}"/>
<constructor-arg index="1">
<set>
<value>${redis.sentine.1}</value>
</set>
</constructor-arg>
<property name="database" value="${redis.dbIndex}"/>
<property name="password" ref="redisPassword"/>
</bean>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<!--注销掉的部分为spring-data-redis2.0以下的版本配置的方式-->
<!-- <property name="hostName" value="${redis.host}"/>
<property name="port" value="${redis.port}"/>
<property name="password" value="${redis.password}" />
<property name="poolConfig" ref="jedisPoolConfig"/>
<property name="database" value="${redis.dbIndex}"/>-->
<!--spring-data-redis2.0以上建议获取的方式-->
<!--<constructor-arg name="poolConfig" ref="jedisPoolConfig"/>
<constructor-arg name="sentinelConfig" ref="redisSentinelConfiguration"/>-->
<constructor-arg name="standaloneConfig" ref="redisStandaloneConfiguration"/>
</bean>
<bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
<!--以下针对各种数据进行序列化方式的选择-->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="enableTransactionSupport" value="true"></property>
</bean>
<!-- 使用中间类解决RedisCache.jedisConnectionFactory的静态注入,从而使MyBatis实现第三方缓存 -->
<bean id="redisCacheTransfer" class="utils.redis.RedisCacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
</bean>
<!-- Redis缓存管理对象 -->
<!-- <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg index = "0" type="RedisOperations">
<ref bean="jedisTemplate" />
</constructor-arg>
</bean> -->
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
factory-method="create" c:connection-factory-ref="jedisConnectionFactory" />
</beans>
RedisCache.java
package utils.redis;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.ibatis.cache.Cache;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.connection.RedisConnection;
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;
public class RedisCache implements Cache {
private static final Logger logger = LogManager.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( "require an ID" );
}
logger.debug( "RedisCache:id=" + id );
this.id = id;
}
@Override
public void clear() {
RedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
connection.flushDb();
connection.flushAll();
} catch( JedisConnectionException e ) {
e.printStackTrace();
} finally {
if( connection != null ) {
connection.close();
}
}
}
@Override
public String getId() {
return this.id;
}
@Override
public Object getObject( Object key ) {
Object result = null;
RedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
result = serializer.deserialize( connection.get( serializer.serialize( key ) ) );
logger.debug( "取Redis内存数据库中的数据Key:" + key + ", value:" + result );
} catch( JedisConnectionException e ) {
e.printStackTrace();
} finally {
if( connection != null ) {
connection.close();
}
}
return result;
}
@Override
public ReadWriteLock getReadWriteLock() {
return this.readWriteLock;
}
@Override
public int getSize() {
int result = 0;
RedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
result = Integer.valueOf( connection.dbSize().toString() );
} catch( JedisConnectionException e ) {
e.printStackTrace();
} finally {
if( connection != null ) {
connection.close();
}
}
return result;
}
@Override
public void putObject( Object key, Object value ) {
RedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
connection.set( serializer.serialize( key ), serializer.serialize( value ) );
logger.debug( "存放到Redis内存数据库中的数据Key:" + key + ", value:" + value );
} catch( JedisConnectionException e ) {
e.printStackTrace();
} finally {
if( connection != null ) {
connection.close();
}
}
}
@Override
public Object removeObject( Object key ) {
RedisConnection 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 static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.jedisConnectionFactory = jedisConnectionFactory;
}
}
RedisCacheTransfer.java
package utils.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Component;
@Component
public class RedisCacheTransfer {
@Autowired
public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
}
}
redis.properties
redis.host=...
redis.master=...
redis.sentine.1=...
redis.port=6379
redis.password=...
redis.timeout=15000
redis.usePool=true
redis.minIdle=100
redis.maxIdle=300
redis.maxTotal=1024
redis.maxActive=300
redis.maxWaitMillis=10000
redis.testOnBorrow=true
redis.pool.testOnReturn=true
redis.pool.timeBetweenEvictionRunsMillis=30000
redis.pool.testWhileIdle=true
redis.pool.numTestsPerEvictionRun=50
MinEvictableIdleTimeMillis=60000
redis.dbIndex = 0
Spring 引入 redis配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Framework</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml,classpath:redis.xml
</param-value>
</context-param>
mybatis引入缓存
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao....Mapper">
<cache type="utils.redis.RedisCache" />