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{
@Cacheble(value="namespace",key="caches[0].name.concat(':').concat(#argument)")
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 {
.
.
.
}