SpringCache

本文介绍了如何在SpringBoot应用中引入Redis作为缓存系统,包括添加依赖、配置application.properties、启用缓存注解@Cacheable以及自定义缓存配置。通过示例展示了如何设置缓存键、存活时间和数据序列化,并提到了缓存失效和更新策略。
摘要由CSDN通过智能技术生成

一、引入依赖

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

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

二、配置

application.properties

spring.cache.type=redis

三、测试使用缓存

  1. 启动类上开启缓存功能
@EnableCaching
  1. 只需要使用注解就能完成缓存操作
// 每一个需要缓存的数据我们都来指定要放到哪个名字的缓存【缓存的分区(按照业务类型分)】
@Cacheable({"category"})  // 代表当前方法的结果需要缓存,如果缓存中有,方法不调用。如果缓存中没有,会调用方法
@Override
public List<CategoryEntity> getLevel1Categorys() {
    System.out.println("getLevel1Categorys...");

    List<CategoryEntity> categoryEntities = this.baseMapper.selectList(
            new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    return categoryEntities;
}

在这里插入图片描述

访问了两次接口,只打印了一次getLevel1Categorys,说明缓存中有,方法不调用
在这里插入图片描述

  • 默认行为
    ○ 如果缓存中有,方法不再调用
    ○ key是默认生成的:缓存的名字::SimpleKey::
    ○ 缓存的value值,默认使用jdk序列化机制,将序列化的数据存到redis中
    ○ 默认时间是 -1

  • 自定义操作:key的生成
    ○ 指定生成缓存的key:key属性指定,接收一个Spel(Spring Expression Language)
      - key若为常量要加单引号,如下
      - @Cacheable(value = {"category"}, key = "'level1Categorys'")
      - SPEL官方文档
      - SPEL中文文档
      - eg:@Cacheable(value = {"category"}, key = "#root.method.name")
    ○ 指定缓存的数据的存活时间:配置文件中修改存活时间
      - spring.cache.redis.time-to-live=360000
    ○ 将数据保存为json格式

@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {

    // @Autowired
    // public CacheProperties cacheProperties;

    /**
     * 配置文件的配置没有用上
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // config = config.entryTtl();
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        //将配置文件中所有的配置都生效
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }

        return config;
    }

}

其他的一些配置

#如果指定了前缀就用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀
#spring.cache.redis.key-prefix=CACHE_
spring.cache.redis.use-key-prefix=true

#是否缓存空值,防止缓存穿透
spring.cache.redis.cache-null-values=true

在这里插入图片描述

@CacheEvict

@CacheEvit就是失效模式:更改数据库缓存就删除

若想一次删除多个缓存,可以 ↓
在这里插入图片描述
也可以 ↓
在这里插入图片描述
在这里插入图片描述
@CachePut就是双写模式:更改数据库的同时也往缓存中存一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值