以Redis为缓存模块的SpringCache使用

来源:互联网 发布:windows.old怎么使用 编辑:程序博客网 时间:2024/06/16 16:13

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 {    .    .    .}
原创粉丝点击