Spring Cache

本文介绍了Spring Cache的使用,包括@Cacheable注解的配置,如cacheNames、key、condition和unless参数的作用。还讨论了condition与unless的区别,并详细讲解了如何配置Redis作为缓存介质,以及如何向Redis缓存中存取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Spring Cache 的使用
  • @Cacheable 注解

    主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,只有使用public定义的方法才可以被缓存,而 private 方法、protected 方法或者使用 default 修饰符的方法都不能被缓存, 当在一个类上使用注解时,该类中每个公共方法的返回值都将被缓存到指定的缓存项中或者从中移除

    cacheNames / value:用于指定缓存存储的集合名

    key:缓存对象存储在Map集合中的key值,非必需,缺省按照函数的所有参数组合作为key值,若自己配置需使用SpringEL表达式

    @Cacheable(key = "#p0") //使用函数第一个参数作为缓存的key值
    

    更多关于SpEL表达式的详细内容可参考官方文档 | 翻译文档

    condition:缓存对象的条件,非必需,也需使用SpringEL表达式,只有满足表达式条件的内容才会被缓存

    // 表示只有当第一个参数的长度小于3的时候才会被缓存
    @Cacheable(key = "#p0", condition = "#p0.length() < 3")
    

    unless:另外一个缓存条件参数,非必需,需使用SpringEL表达式。它不同于condition参数的地方在于它的判断时机,该条件是在函数被调用之后才做判断的,所以它可以对result进行判断

    @Cacheable(value = "params_details", key = "#publicKey", unless = "#result == null ")
    

    condition 与 unless 作用都是排除满足条件的结果(满足条件不进行缓存)

    condition 与 unless 的区别:

    • condition:对参数进行判断
    • unless:对结果进行判断

    sync:是否使用异步模式。

  • 获取缓存中的参数

    CacheManager负责对缓存的增删改查, CacheManager的缓存的介质可配置, 如:ConcurrentMap/EhCache/Redis等。当没有加入EhCache或者Redis依赖时默认采用concurrentMap实现的缓存,是存在内存中,重启服务器则清空缓存

    @Resouce
    private final CacheManager cacheManager;
    
    public Object getCacheValue() {
    	return cacheManager.getCache(CACHE_KEY);
    }
    
2、Spring Cache 存取缓存数据
  • 设置缓存的介质

    默认采用concurrentMap实现的缓存,是存在内存中,重启服务器则清空缓存

    设置 redis 为缓存介质

    spring:
      cache:
        type: redis
      redis:
        host: 127.0.0.1
        port: 6379
        password: 123456
    
  • 添加依赖

    <!--多级缓存-->
    <dependency>
    	<groupId>com.pig4cloud.plugin</groupId>
    	<artifactId>multilevel-cache-spring-boot-starter</artifactId>
    	<version>1.0.1</version>
    </dependency>
    
  • 向缓存中存储数据

    使用 @Cacheable 注解的方式做缓存操作:

    value:redis 分组集合

    key:分组集合中指向存储对象的键

    unless:设置缓存条件(排除符合条件的结果)

    @RequestMapping(method = RequestMethod.POST)
    @Cacheable(value = "Test" ,key = "'Cache'", unless = "#result == null")
    public String cache() {
    	return "CacheValue";
    }
    
  • 从缓存中获取数据

    @Autowired
    private final CacheManager cacheManager;
    
    @RequestMapping(method = RequestMethod.GET)
    public Object getCacheValue() {
    	Cache cache = cacheManager.getCache("Test");
    	if (cache != null && cache.get("Cache") != null) {
    		return cache.get("Cache").get();
    	}
    	return "error";
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值