基于Redis的SpringCache的使用实战
1、pom文件中,导入maven依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
2、在SpringMVC配置文件中,引入classes类路径下的Redis配置文件
<context-property-placehoder location="classpath:redis.properties" />
3、配置缓存管理器,开启Spring对缓存的支持
<!--开启Spring对缓存的支持-->
<cache:annotation-driven />
<!--配置以Redis为缓存模块的缓存管理器-->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:hostName="${redis.host}"
p:port="${redis.port}"
/>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
<property name="keySerializer" >
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
</bean>
<!--配置缓存管理器-->
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager" >
<constructor-arg ref="redisTemplate"></constructor-arg>
</bean>
4、在Service的查询方法中使用缓存
public class ServiceImpl{
//value自定义的存储空间名称,
//key,存储空间下所缓存对象的key值,使用Spring的EL表达式获取参数中的值,
//unless,默认缓存所有查出来的对象,当SpringEL表达式的结果为true时不缓存,也就是说查询结果为null时,不缓存,可以避免很多bug
@Cacheble(value="namespace",key="#argument",unless="#result==null")
public Object findByArgument(argument){
.
.
.
return Object;
}
}
5、定义使缓存失效的方法,一般为对所缓存对象的增、删的方法,如果方法参数不能获取与缓存对象对应的key值,应该使在方法参数中增加一个key值
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RuntimeException.classException.class})
//更新缓存对象时,使缓存失效,下次使用时执行真正的查询动作
@CacheEvict(value="namespace",key="(#argument)")
public int updateMethod(Object argument) throws Exception {
.
.
.
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RuntimeException.class, Exception.class})
//删除所缓存对象时,使已经缓存的对象失效
@CacheEvict(value="namespace",key="(#argument)")
public int updateCredenceForEdit(Object argument) throws Exception {
.
.
.
}
For you,a thousand times over.为了你,千千万万遍。