分布式缓存Spring Cache

一、缓存里的数据如何和数据库的数据保持一致?

如果实时性、一致性要求高的,不是读多写少的,就直接去数据库查,不必缓存到redis中,不必过度设计

1、缓存数据一致性-双写模式

在这里插入图片描述
伪代码如下:

public boolean saveToDb() {
         //1.更新数据库
        baseMapper.insert(category);
        //2.更新缓存数据
        stringRedisTemplate.opsForValue().set("key","value");
}

2、 缓存数据一致性-失效模式

在这里插入图片描述
伪代码如下:

public boolean saveToDb() {
         //1.更新数据库
        baseMapper.insert(category);
        //2.删除缓存数据
        stringRedisTemplate.delete("key");
}

//3.需要用到缓存数据的另一方法再去查询数据库,再保存到缓存中

3、能容忍暂时性脏数据的存在,只要能实现最终一致性,可将缓存数据添加过期时间,能够解决大部分业务问题

#spring.cache.cache-names=qq,毫秒为单位
spring.cache.redis.time-to-live=3600000

4、读写锁+删除或更新缓存数据/过期时间(我们系统的一致性解决方案)

缓存的所有数据都有过期时间,数据过期下一次查询触发主动更新
读写数据的时候,加上分布式的读写锁。经常读写对此会有很大的影响

#spring.cache.cache-names=qq,毫秒为单位
spring.cache.redis.time-to-live=3600000
/**
  *  写数据用写锁
  * 级联更新所有关联的数据
  */
  @CacheEvict(value = "category", allEntries = true)//删除某个分区下的所有数据
  @Override
  public void updateCascade(CategoryEntity category) {

        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("catalogJson-lock");
        //创建写锁
        RLock rLock = readWriteLock.writeLock();

        try {
            rLock.lock();
            this.baseMapper.updateById(category);
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
            //删除或更新缓存数据
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
   }

/**
  *  读数据用读锁
  * 级联更新所有关联的数据
  */
public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {

        //1、占分布式锁。去redis占坑
        //(锁的粒度,越细越快:具体缓存的是某个数据,11号商品) product-11-lock
        //RLock catalogJsonLock = redissonClient.getLock("catalogJson-lock");
        //创建读锁
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("catalogJson-lock");

        RLock rLock = readWriteLock.readLock();

        Map<String, List<Catelog2Vo>> dataFromDb = null;
        try {
            rLock.lock();
            //加锁成功...执行业务
            dataFromDb = getDataFromDb();
        } finally {
            rLock.unlock();
        }
        return dataFromDb;
}

总结:缓存数据一致性-解决方案

在这里插入图片描述

5、缓存数据一致性-解决-Canal

在这里插入图片描述

二、Spring Cache简介

1、 Spring 从 3.1 开始定义了org.springframework.cache.Cache和 org.springframework.cache.CacheManager 接口来统一不同的缓存技术;并支持使用 JCache(JSR-107)注解简化我们开发;

2、Cache 接口为缓存的组件规范定义,包含缓存的各种操作集合;Cache 接 口 下 Spring 提 供 了 各 种 xxxCache 的 实 现 ; 如 RedisCache , EhCacheCache , ConcurrentMapCache 等;

3、 每次调用需要缓存功能的方法时,Spring 会检查检查指定参数的指定的目标方法是否已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓存结果后返回给用户。下次调用直接从缓存中获取。

4、 使用 Spring 缓存抽象时我们需要关注以下两点;
(1)、确定方法需要被缓存以及他们的缓存策略
(2)、从缓存中读取之前缓存存储的数据

三、Spring Cache基础概念

在这里插入图片描述

四、Spring Cache注解

在这里插入图片描述
在这里插入图片描述

五、Spring Cache表达式语法

在这里插入图片描述

六、整合SpringCache简化缓存开发

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)、写配置

(1)、自动配置了哪些?
CacheAutoConfiguration会导入 RedisCacheConfiguration;
自动配好了缓存管理器RedisCacheManager

(2)、配置使用redis作为缓存,配置文件

spring.cache.type=redis
#spring.cache.cache-names=qq,毫秒为单位
spring.cache.redis.time-to-live=3600000

#生产一般不写,如果指定了前缀就用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀
spring.cache.redis.key-prefix=CACHE_
#是否使用key前缀
spring.cache.redis.use-key-prefix=true
#是否缓存空值。防止缓存穿透
spring.cache.redis.cache-nul1-values=true

3)、配置类
原理:CacheAutoConfiguration -> RedisCacheConfiguration ->自动配置了RedisCacheManager->初始化所有的缓存->每个缓存决定使用什么配置->如果redisCacheConfiguration有就用已有的,没有就用默认配置

package com.product.config;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@EnableConfigurationProperties(CacheProperties.class)
@Configuration
//如果启动类有可将其去除,开启缓存功能
@EnableCaching
public class MyCacheConfig {

    // @Autowired
    // public CacheProperties cacheProperties;

    /**
     * 配置文件的配置没有用上
     *   1、原来和配置文件绑定的配置类是这样子的
     *       @ConfigurationProperties(prefix = “spring.cache")
     *       public class CacheProperties
         2、要让他生效
              @EnableConfigurationProperties(CacheProperties.class)
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // config = config.entryTtl();
        //key指定序列化
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //value指定序列化
        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;
    }

}

4)、测试使用缓存
@Cacheable: 触发将数据保存到缓存的操作
@CacheEvict: 触发将数据从缓存删除的操作
@CachePut: 不影响方法执行更新缓存
@Caching:组合以上多个操作
@CacheConfig: 在类级别共享缓存的相同配置

4.1)、只需要使用注解就能完成缓存操作

   /**
     * 1.缓存key指定:每一个需要缓存的数据,我们都来指定要放到那个名字的缓存。【缓存的分区(按照业务类型分)】
     * 2.代表当前方法的结果需要缓存,如果缓存中有,方法都不用调用,如果缓存中没有,会调用方法。最后将方法的结果放入缓存
     * 3.默认行为
     *      如果缓存中有,方法不再调用
     *      key是默认生成的:缓存的名字::SimpleKey::[](自动生成key值)
     *             如:category::SimpleKey[]
     *      缓存的value值,默认使用jdk序列化机制,将序列化的数据存到redis中
     *      默认时间是 -1:
     *
     * 4.需自定义操作:key的生成
     *      指定生成缓存的key:key属性指定,接收一个Spel
     *           如:category::getLevel1Categorys
     *      指定缓存的数据的存活时间:配置文件中修改存活时间
     *            spring.cache.redis.time-to-live=3600000
     *      将数据保存为json格式
     *

     *
     *  原理:
     *      CacheManager(RedisCacheManager)->Cache(RedisCache)->Cache负责缓存的读写
     * @return
     */
     //如果配置文件配置了spring.cache.redis.key-prefix=CACHE_,则key为CACHE_getLevel1Categorys,value = {"category"}则无用
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys........");
        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println("消耗时间:"+ (System.currentTimeMillis() - l));
        return categoryEntities;
    }

4.2 )、Spring Cache注解扩展介绍

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     * @CacheEvict:删除指定key的缓存,对应失效模式
     * @CachePut:更新缓存,对应双写模式,需要有返回值
     * @Cacheable:将数据保存到缓存的操作
     * 1、同时进行多种缓存操作:
     *     @Caching
     * 2、指定删除某个分区下的所有数据 
     *     @CacheEvict(value = "category",allEntries = true)
     * 3、存储同一类型的数据,都可以指定为同一分区
     */
    //1.一个一个删除
    // @Caching(evict = {
    //         @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
    //         @CacheEvict(value = "category",key = "'getCatalogJson'")
    // })
    //2.批量删除某个分区下的所有数据
    @CacheEvict(value = "category", allEntries = true)       
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCascade(CategoryEntity category) {

        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("catalogJson-lock");
        //创建写锁
        RLock rLock = readWriteLock.writeLock();

        try {
            rLock.lock();
            this.baseMapper.updateById(category);
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }

        //同时修改缓存中的数据
        //删除缓存,等待下一次主动查询进行更新
    }

总结:Spring-Cache的不足之处:

   1)、读模式
       缓存穿透:查询一个null数据。解决方案:缓存空数据
       缓存击穿:大量并发进来同时查询一个正好过期的数据。解决方案:加锁 ? 默认是无加锁的;使用sync = true来解决击穿问题
       缓存雪崩:大量的key同时过期。解决:加随机时间。加上过期时间
   2)、写模式:(缓存与数据库一致)
       1)、读写加锁。
       2)、引入Canal,感知到MySQL的更新去更新Redis
       3)、读多写多,直接去数据库查询就行
总结:
   常规数据(读多写少,即时性,一致性要求不高的数据,完全可以使用Spring-Cache):写模式(只要缓存的数据有过期时间就足够了)
   特殊数据:特殊设计
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值