SpringCache整合redis和Springboot的使用方法

1、引入以下依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2、添加如下配置

spring:
  redis:
    host: 192.168.209.128
    port: 6379
  cache:
    type: redis
    redis:
      time-to-live: 3600000
      cache-null-values: true #允许缓存为null,防止缓存穿透

3、在启动类或配置类中添加@EnableCaching注解,并配置json序列化,代码如下

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    RedisCacheConfiguration redisCacheConfiguration(){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config=config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config=config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return config;
    }
}

我就是因为没有添加@EnableCaching注解,导致缓存不起作用,无法添加缓存,折腾了很久才发现,特此说明。

4、给servie层中的方法添加缓存注解

@Override
@CacheEvict(value = "HouseResources",allEntries = true)
public boolean save(HouseResources houseResources){
    int result = apiHouseResourceService.saveHouseResources(houseResources);
    return result==1;
}

@Override
@Cacheable(value = "HouseResources",key = "'queryList_'+#current+'_'+#size")
public TableResult<HouseResources> queryList(HouseResources houseResources, Integer current, Integer size) {
    PageInfo<HouseResources> pageInfo = apiHouseResourceService.queryHouseResourcesList(current, size, houseResources);
    return new TableResult<HouseResources>(pageInfo.getRecords(),new Pagination(current,size,pageInfo.getTotal()));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值