SpringBoot整合Spring Cache

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: SpringBoot整合Spring Cache


开始整合

引入依赖

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

配置

spring:
  redis:
    host: 192.168.100.10
    port: 6379
spring.cache.type=redis
spring.cache.redis.time-to-live=30000

常用注解

@Cacheable(value = {"category"},key = "'level1Categorys'")

验证

@Cachable注解

value指定分区,key值,不指定前缀那么就使用value分区

存在的问题

可以看到cache默认返回的不是json数据类型,默认使用的是java自带的解析器,因此我们需要将其修改为json格式的,这样保证跨平台数据传输。

在cache中默认自动进行了很多配置,这里是一个配置选择器,如果我们在配置文件中选择了一个缓存类型那么相关的配置就会加载进去。

在这个加载的Redis缓存配置文件中可以看到如果Redis配置是空那么就进行默认的配置,所以我们可以根据这个来进行自定义配置

在这个配置项中我们要开启CacheProperties去拿到Redis的配置文件里的配置。

@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {
    @Bean
    RedisCacheConfiguration cacheConfiguration(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;
    }
}

@CacheEvict注解:

用于更新操作中,更新后将缓存中指定数据清除,也就是使用失效模式保证数据的一致性问题

@CacheEvict(value = {"category"},key = "'getLevel1Categorys'"),
@CacheEvict(value = {"category"},allEntries = true)     //allEntries 开启后将category分区下的所有缓存数据都删除

@Caching

用于多个缓存注解联合操作

@Caching(evict = {
        @CacheEvict(value = {"category"},key = "'getLevel1Categorys'"),
        @CacheEvict(value = {"category"},key = "'getCatelogJson'")
})

Cache和Redisson

Cache保证了缓存中有数据直接返回,如果缓存中没有数据开始加锁,执行查询数据库的业务,然后搭配@CacheEvict使用失效模式保证数据的一致性

@Cacheable(value = {"category"},key = "#root.methodName")
@Override
public Map<String, List<Catelog2VO>> getCatelogJson()  {
    RLock lock = redisson.getLock("catelogJson-lock");
    lock.lock();
    Map<String, List<Catelog2VO>> dataFromDB = null;
    //加锁成功。。。执行业务
    //设置过期时间,必须和加锁是同步的原子的
    try {
        dataFromDB = getCatelogJsonFromDB();
    } finally {
        lock.unlock();
    }
    return dataFromDB;
}
@Caching(evict = {
            @CacheEvict(value = {"category"},key = "'getLevel1Categorys'"),
            @CacheEvict(value = {"category"},key = "'getCatelogJson'")
    })
//    @CacheEvict(value = {"category"},allEntries = true)
    @Override
    public void updateDetails(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotEmpty(category.getName())) {
            categoryBrandRelationService.updateCategoryName(category.getCatId(), category.getName());
        }
    }

不足

读模式:

  • 缓存穿透:当查询某一个是空的数据,一直在缓存中查不到压力给到了数据库,解决方法:cache默认给空数据设置null,防止了缓存穿透
  • 缓存雪崩:大量的key全部过期,解决方法:设置过期时间 spring.cache.redis.time-to-live=30000
  • 缓存击穿:当某一个key过期的一瞬间大量请求同时进入。解决方法:加锁(Redisson或者使用cache自带的本地锁@Cacheable(value = {“category”},key = “#root.methodName”,sync = true))

写模式:

  • 读写锁
  • 引入Canal,感知数据库的更新去更新缓存
  • 读多写少直接去数据库查

总结:

  • 常规数据(读多写少、及时性、一致性要求不高的数据)可以使用cache
  • 特殊数据:特殊设计
相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
19天前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
|
2月前
|
缓存 NoSQL Java
SpringBoot的三种缓存技术(Spring Cache、Layering Cache 框架、Alibaba JetCache 框架)
Spring Cache 是 Spring 提供的简易缓存方案,支持本地与 Redis 缓存。通过添加 `spring-boot-starter-data-redis` 和 `spring-boot-starter-cache` 依赖,并使用 `@EnableCaching` 开启缓存功能。JetCache 由阿里开源,功能更丰富,支持多级缓存和异步 API,通过引入 `jetcache-starter-redis` 依赖并配置 YAML 文件启用。Layering Cache 则提供分层缓存机制,需引入 `layering-cache-starter` 依赖并使用特定注解实现缓存逻辑。
349 1
SpringBoot的三种缓存技术(Spring Cache、Layering Cache 框架、Alibaba JetCache 框架)
|
2月前
|
Java 微服务 Spring
SpringBoot+Vue+Spring Cloud Alibaba 实现大型电商系统【分布式微服务实现】
文章介绍了如何利用Spring Cloud Alibaba快速构建大型电商系统的分布式微服务,包括服务限流降级等主要功能的实现,并通过注解和配置简化了Spring Cloud应用的接入和搭建过程。
SpringBoot+Vue+Spring Cloud Alibaba 实现大型电商系统【分布式微服务实现】
|
2月前
|
安全 Java 数据安全/隐私保护
基于SpringBoot+Spring Security+Jpa的校园图书管理系统
本文介绍了一个基于SpringBoot、Spring Security和JPA开发的校园图书管理系统,包括系统的核心控制器`LoginController`的代码实现,该控制器处理用户登录、注销、密码更新、角色管理等功能,并提供了系统初始化测试数据的方法。
36 0
基于SpringBoot+Spring Security+Jpa的校园图书管理系统
|
2月前
|
安全 Java 数据库
|
2月前
|
JSON 安全 Java
|
2月前
|
Java Spring
【Azure 事件中心】Spring Boot 集成 Event Hub(azure-spring-cloud-stream-binder-eventhubs)指定Partition Key有异常消息
【Azure 事件中心】Spring Boot 集成 Event Hub(azure-spring-cloud-stream-binder-eventhubs)指定Partition Key有异常消息
|
2月前
|
前端开发 Java Spring
Java 新手入门:Spring Boot 轻松整合 Spring 和 Spring MVC!
Java 新手入门:Spring Boot 轻松整合 Spring 和 Spring MVC!
48 0
|
Java 应用服务中间件 Spring
Netweaver的端口号和Spring boot内嵌的Tomcat端口
Netweaver的端口号和Spring boot内嵌的Tomcat端口
Netweaver的端口号和Spring boot内嵌的Tomcat端口
|
9天前
|
前端开发 JavaScript Java
基于Java+Springboot+Vue开发的服装商城管理系统
基于Java+Springboot+Vue开发的服装商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的服装商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
31 2
基于Java+Springboot+Vue开发的服装商城管理系统
下一篇
无影云桌面