SpringBoot 缓存之 @Cacheable 详细介绍

这篇具有很好参考价值的文章主要介绍了SpringBoot 缓存之 @Cacheable 详细介绍。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、简介

1、缓存介绍

Spring 从 3.1 开始就引入了对 Cache 的支持。定义了 org.springframework.cache.Cache 和 org.springframework.cache.CacheManager 接口来统一不同的缓存技术。并支持使用 JCache(JSR-107)注解简化我们的开发。
其使用方法和原理都类似于 Spring 对事务管理的支持。Spring Cache 是作用在方法上的,其核心思想是,当我们在调用一个缓存方法时会把该方法参数和返回结果作为一个键值对存在缓存中。

2、Cache 和 CacheManager 接口说明
  • Cache 接口包含缓存的各种操作集合,你操作缓存就是通过这个接口来操作的。
  • Cache 接口下 Spring 提供了各种 xxxCache 的实现,比如:RedisCache、EhCache、ConcurrentMapCache
  • CacheManager 定义了创建、配置、获取、管理和控制多个唯一命名的 Cache。这些 Cache 存在于 CacheManager 的上下文中。

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

二、@Cacheable 注解使用详细介绍

1、缓存使用步骤

@Cacheable 这个注解,用它就是为了使用缓存的。所以我们可以先说一下缓存的使用步骤:

1、开启基于注解的缓存,使用 @EnableCaching 标识在 SpringBoot 的主启动类(或配置类)上。

2、标注缓存注解即可

① 第一步:开启基于注解的缓存,使用 @EnableCaching 标注在 springboot 主启动类上

@SpringBootApplication
@EnableCaching/**开启基于注解的缓存*/
@Slf4j
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        log.info("<<===================   启动成功   ==================>>");
    }

}

② 第二步:标注缓存注解

    @Cacheable(value = "test",key = "#id")
    public String test(Integer id){
        System.out.println("经过这里=======>");
        return "这是测试"+id;
    }

:这里使用 @Cacheable 注解就可以将运行结果缓存,以后查询相同的数据,直接从缓存中取,不需要调用方法,若数据过期,需要调用方法查询结果返回并缓存

2、常用属性说明

下面介绍一下 @Cacheable 这个注解常用的几个属性:

  • cacheNames/value :用来指定缓存组件的名字
  • key :缓存数据时使用的 key,可以用它来指定。默认是使用方法参数的值。(这个 key 你可以使用 spEL 表达式来编写)
  • keyGenerator :key 的生成器。 key 和 keyGenerator 二选一使用
  • cacheManager :可以用来指定缓存管理器。从哪个缓存管理器里面获取缓存。
  • condition :可以用来指定符合条件的情况下才缓存
  • unless :否定缓存。当 unless 指定的条件为 true ,方法的返回值就不会被缓存。当然你也可以获取到结果进行判断。(通过 #result 获取方法结果)
  • sync :是否使用异步模式。
  1. cacheNames/value
    用来指定缓存组件的名字,将方法的返回结果放在哪个缓存中,可以是数组的方式,支持指定多个缓存。
  2. key
    缓存数据时使用的 key。默认使用的是方法参数的值。可以使用 spEL 表达式去编写
  3. keyGenerator
    key 的生成器,可以自己指定 key 的生成器,通过这个生成器来生成 key
    @cacheable keygenerator,spring boot,缓存,spring,redis
    @cacheable keygenerator,spring boot,缓存,spring,redis
    这样放入缓存中的 key 的生成规则就按照你自定义的 keyGenerator 来生成。不过需要注意的是:
    @Cacheable 的属性,key 和 keyGenerator 使用的时候,一般二选一。
  4. condition
    符合条件的情况下才缓存。方法返回的数据要不要缓存,可以做一个动态判断。
    @cacheable keygenerator,spring boot,缓存,spring,redis
  5. unless
    否定缓存。当 unless 指定的条件为 true ,方法的返回值就不会被缓存。
    @cacheable keygenerator,spring boot,缓存,spring,redis
  6. sync
    是否使用异步模式。默认是方法执行完,以同步的方式将方法返回的结果存在缓存中。

前面说过,缓存的 key 支持使用 spEL 表达式去编写,下面总结一下使用 spEL 去编写 key 可以用的一些元数据:

属性名称 描述 示例
methodName 当前方法名 #root.methodName
method 当前方法 #root.method.name
target 当前被调用的对象 #root.target
targetClass 当前被调用的对象的class #root.targetClass
args 当前方法参数组成的数组 #root.args[0]
caches 当前被调用的方法使用的Cache #root.caches[0].name
3、@CachePut和@CacheEvict 注解使用
  • @CachePut
    将方法返回值存入到缓存中,一般情况下是用在更新操作中,并于Cacheable与CacheEvict配合使用
  • @CacheEvict
    清除缓存值,一般用在删除或更新操作中,并于Cacheable与CachePut配合使用。并且在@CacheEvict注解中,多了两个参数:
  1. allEntries - 清除当前value下的所有缓存
  2. beforeInvocation - 在方法执行前清除缓存

示例代码示例如下:

	/**查询,加载缓存*/
	@Cacheable(value = "c", key = "123")
    public String hello(String name) {
        System.out.println("name - " + name);
        return "hello " + name;
    }
    
    /**更新缓存*/
    @CachePut(value = "c", key = "123")
    public String put() {
        return "hello put";
    }
    
    /**删除缓存*/
    @CacheEvict(value = "c", key = "123")
    public String evict() {
        return "hello put";
    }

三、配置类(结合Redis作为缓存)

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * 缓存配置类
 * */
@EnableCaching /**开启缓存注解*/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        /**解决查询缓存转换异常的问题*/
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        /**配置序列化(解决乱码的问题)*/
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))/**设置缓存默认过期时间600秒*/
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        return RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
    }

}

pom.xml需要Redis依赖:

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

纯属个人经验,喜欢的可以点赞关注,后续见!!!文章来源地址https://www.toymoban.com/news/detail-860010.html

到了这里,关于SpringBoot 缓存之 @Cacheable 详细介绍的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • @EnableCaching、@Cacheable的介绍,及Redis在SpringBoot中的使用教程

    首先说明这两个注解都是spring提供的,可以结合不同的缓存技术使用。(这里将顺便结合Redis进行讲解) 1.1 @EnableCaching @EnableCaching是开启缓存功能,作用于缓存配置类上或者作用于springboot启动类上。 1.2 @Cacheable @Cacheable 注解在方法上,表示该方法的返回结果是可以缓存的。也

    2024年01月24日
    浏览(38)
  • @Cacheable 注解(指定缓存位置)

    1、缓存使用步骤:@Cacheable这个注解,用它就是为了使用缓存的。所以我们可以先说一下缓存的使用步骤: 1、开启基于注解的缓存,使用 @EnableCaching 标识在 SpringBoot 的主启动类上。 2、标注缓存注解即可  使用  @Cacheable  注解就可以将运行结果缓存,以后查询相同的数据,

    2024年02月07日
    浏览(40)
  • redis缓存神器:@Cacheable注解

    在之前的文章中,我们写了redis结合springboot做缓存分页的方法: 在 Spring Boot 中结合 Redis 进行缓存分页数据,可以通过以下步骤实现: 在 pom.xml 文件中添加 Redis 相关依赖: 在 application.properties 文件中配置 Redis 连接信息: 创建一个 RedisTemplate 对象,用于操作 Redis 缓存: 在

    2024年02月06日
    浏览(41)
  • @EnableCaching @Cacheable @CachePut redis注解缓存

    @EnableCaching注解是spring framework中的注解驱动的缓存管理功能。自spring版本3.1起加入了该注解。如果你使用了这个注解,那么你就不需要在XML文件中配置cache manager了。 当你在配置类(@Configuration)上使用@EnableCaching注解时,会触发一个post processor,这会扫描每一个spring bean,查看是

    2024年02月13日
    浏览(45)
  • Spring 中的 @Cacheable 缓存注解,太好用了!

    第一个问题,首先要搞明白什么是缓存,缓存的意义是什么。 对于普通业务,如果要查询一个数据,一般直接select数据库进行查找。但是在高流量的情况下,直接查找数据库就会成为性能的瓶颈。因为数据库查找的流程是先要从磁盘拿到数据,再刷新到内存,再返回数据。磁

    2024年02月16日
    浏览(29)
  • 转载 spring @Cacheable扩展实现缓存自动过期时间以及自动刷新

    用过spring cache的朋友应该会知道,Spring Cache默认是不支持在@Cacheable上添加过期时间的,虽然可以通过配置缓存容器时统一指定。形如 复制 但有时候我们会更习惯通过注解指定过期时间。今天我们就来聊一下如何扩展@Cacheable实现缓存自动过期以及缓存即将到期自动刷新 2 实现

    2024年02月03日
    浏览(30)
  • 一文掌握SpringBoot注解之@Cacheable 知识文集(1)

    🏆作者简介,普修罗双战士,一直追求不断学习和成长,在技术的道路上持续探索和实践。 🏆多年互联网行业从业经验,历任核心研发工程师,项目技术负责人。 🎉欢迎 👍点赞✍评论⭐收藏 🔎 SpringBoot 领域知识 🔎 链接 专栏 SpringBoot 专业知识学习一 SpringBoot专栏 Sprin

    2024年01月20日
    浏览(34)
  • Spring Boot 中的 @Cacheable 注解

    在 Spring Boot 中,缓存是一个非常重要的话题。当我们需要频繁读取一些数据时,为了提高性能,可以将这些数据缓存起来,避免每次都从数据库中读取。为了实现缓存,Spring Boot 提供了一些缓存注解,其中最常用的是 @Cacheable 注解。 @Cacheable 注解用于标记一个方法需要被缓存

    2024年02月12日
    浏览(51)
  • spring cache 学习 —— @Cacheable 使用详解

    @Cacheable 注解在方法上,表示该方法的返回结果是可以缓存的。也就是说,该方法的返回结果会放在缓存中,以便于以后使用相同的参数调用该方法时,会返回缓存中的值,而不会实际执行该方法。 注意,这里强调了一点:参数相同。 这一点应该是很容易理解的,因为缓存不

    2024年02月03日
    浏览(33)
  • @EnableCaching,@Cacheable, @CachePut,@CacheEvict详解

    在Spring Boot中,可以通过@EnableCaching注解启用缓存功能,并结合Redis作为缓存实现。下面是一个使用@EnableCaching注解并结合Redis使用的示例: 添加Redis依赖,在pom.xml文件中添加以下依赖: application.yml 配置Redis连接信息 指定缓存类型 redis 在启动类XXApplication.java主类中中加入注解

    2024年02月11日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包