广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot2.X整合Spring-Cache缓存开发的实现
  • 432
分享到

SpringBoot2.X整合Spring-Cache缓存开发的实现

2024-04-02 19:04:59 432人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录引入依赖配置测试使用缓存@Cacheable注解的使用@CacheEvict注解的使用@Caching注解的使用@CachePut注解的使用spring-Cache的不足读模式写

引入依赖

<!-- 引入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
  • 只需要使用注解就能完成缓存操作

@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 {

    
    @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注解的使用

数据一致性中的失效模式


// @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注解的使用


@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。写模式:只要缓存的数据有过期时间就足够了

到此这篇关于SpringBoot2.X整合Spring-Cache缓存开发的实现的文章就介绍到这了,更多相关SpringBoot Spring-Cache缓存 内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot2.X整合Spring-Cache缓存开发的实现

本文链接: https://www.lsjlt.com/news/165097.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作