以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{
     //自定义的存储空间名称
    @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 {
    .
    .
    .
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值