ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SpringBoot2.X整合Spring-Cache简化缓存开发

2022-01-05 22:33:55  阅读:160  来源: 互联网

标签:category cache Spring Cache 缓存 SpringBoot2 key spring config


引入依赖

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

配置

  • 自动配置

    CacheAutoConfiguration会导入 RedisCacheConfiguration;自动配置好了缓存管理器RedisCacheManager

  • 配置使用redis作为缓存

spring.cache.type=redis

测试使用缓存

  • @Cacheable: Triggers cache population. 触发将数据保存到缓存的操作

  • @CacheEvict: Triggers cache eviction. 触发将数据从缓存删除的操作

  • @CachePut: Updates the cache without interfering with the method execution.不影响方法执行更新缓存

  • @Caching: Regroups multiple cache operations to be applied on a method.组合以上多个操作

  • @CacheConfig: Shares some common cache-related settings at class-level.在类级别共享缓存的相同配置

@Cacheable注解的使用

  • config中开启缓存功能 @EnableCaching

  • 只需要使用注解就能完成缓存操作

/**
 * 1、每一个需要缓存的数据我们都来指定要放到哪个名字的缓存。【缓存的分区(按照业务类型分)】
 * 2、@Cacheable({"category"})
 *      代表当前方法的结果需要缓存,如果缓存中有,方法不再调用。
 *      如果缓存中没有,会调用方法,最后将方法的结果放入缓存。
 * 3、默认行为
 *      1)、如果缓存中有,方法不用调用。
 *      2)、key默认自动生成:格式:缓存的名字::SimpleKey [](自主生成的key值) 例:category::SimpleKey []
 *      3)、缓存的value值,默认使用jdk序列化机制。将序列化后的数据存到redis
 *      4)、默认ttl时间:-1;
 *
 *   自定义:
 *      1)、指定生成的缓存使用的key key属性指定,接受一个SpEl @Cacheable(value = {"category"}, key = "#root.method.name")
 				key的SpEl可以参考:https://docs.spring.io/spring-framework/docs/5.2.19.RELEASE/spring-framework-reference/integration.html#cache-spel-context

 *      2)、指定缓存的数据的存活时间 spring.cache.redis.time-to-live=3600000
 *      3)、将数据保存为json格式
 *
 *
 * @return
 */
@Cacheable(value = {"category"}, key = "#root.method.name")
@Override
public List<CategoryEntity> findCatelog1() {
  System.out.println("查询数据库---");
  return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
}

  • 指定缓存数据的存活时间

    spring.cache.redis.time-to-live=3600000
    
  • 将数据保存为json格式:配置

    @EnableConfigurationProperties(CacheProperties.class)
    @Configuration
    @EnableCaching // 开启缓存
    public class MyCacheConfig {
    
        /**
         * 配置文件中的东西没有用上
         *
         * 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.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注解的使用

  • 数据一致性中的失效模式
/**
 * 使用失效模式:先删除缓存,在访问系统获得缓存
 * findCatelog1:缓存时的key名
 * value = "category" 需要与缓存时的名称相同
 * 存储同一个类型的数据,都可以指定成同一个分区。分区名默认就是缓存的前缀
 */
// @CacheEvict(value = "category", key = "'findCatelog1'")// 删除具体key的缓存
@CacheEvict(value = "category", allEntries = true)// 指定删除某个分区下的所有数据
@Transactional
@Override
public void updateCascade(CategoryEntity category) {
  this.updateById(category);
  categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
}
  • 数据一致性中的双写模式,使用@CachePut注解

@Caching注解的使用

/**
 * @CacheEvict: 失效模式:先删除缓存,在访问系统获得缓存
 * 1、同时进行多种缓存操作  @Caching
 * 2、指定删除某个分区下的所有数据
 * @param category
 */
@Caching(evict = {
  @CacheEvict(value = "category", key = "'findCatelog1'"),// 删除缓存
  @CacheEvict(value = "category", key = "'getCatalogJson'"),// 删除缓存
})
@Transactional
@Override
public void updateCascade(CategoryEntity category) {
  this.updateById(category);
  categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
}

@CachePut注解的使用

  • 数据一致性中的双写模式
@CachePut // 双写模式时使用

Spring-Cache的不足

读模式

  • 缓存穿透:查询一个null数据。解决:缓存空数据:spring.cache.redis.cache-null-values=true

  • 缓存雪崩:大量的key同时过期。解决:加随机时间,加上过期时间。spring.cache.redis.time-to-live=3600000

  • 缓存击穿:大量并发同时查询一个正好过期的数据。解决:加锁。SpringCache默认是没有加锁的。

    @Cacheable(value = {"category"}, key = "#root.method.name", sync = true)
    sync = true 相当于是加本地锁,可以用来解决击穿问题
    

写模式

  • 读写加锁
  • 引入Canal,感知到MySQL的更新去更新数据库
  • 读多写多,直接去数据库查询就行

总结

常规数据(读多写少,即时性,一致性要求不高的数据),完全可以使用Spring-Cache。写模式:只要缓存的数据有过期时间就足够了

特殊数据:特殊设计

标签:category,cache,Spring,Cache,缓存,SpringBoot2,key,spring,config
来源: https://blog.csdn.net/m0_62415474/article/details/122333358

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有