首页 > 其他分享 >SpringBoot的开启缓存@EnableCaching 和 使用缓存@Cacheable

SpringBoot的开启缓存@EnableCaching 和 使用缓存@Cacheable

时间:2023-02-20 19:07:53浏览次数:43  
标签:缓存 SpringBoot default 指定 Cacheable key String

springboot中的缓存注解支持Spel表达式,因此这里展示常用的SpEL表达式

1、开启缓存

@EnableCaching

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

2、使用缓存

@Cacheable

该注解的作用是将方法的返回结果做缓存

在需要缓存的地方使用@Cacheable注解,例如在service中使用

默认情况 key就是参数名,key可以指定哪个参数名作为缓存的键

使用方式是#a0 #p0 #参数名 #root.args[0]都是指定同一个参数,后面的数字就是选择哪个参数作为键

@Cacheable中的方法

使用方式都是@Cacheable(key=xxx, cacheNames={“name1”,“name2”} …),根据需要添加

	//与cacheNames相同,@AliasFor是取别名
    @AliasFor("cacheNames")
    String[] value() default {};
    @AliasFor("value")
    //缓存组件名,数据存在缓存组件中以key:value的形式存储
    String[] cacheNames() default {};
    
	//与keyGenerator 2选1只能用一个,就是缓存的key
    String key() default "";
	//key的生成器;可以自己指定key的组件id 与上面的key二选一使用
    String keyGenerator() default "";
	//指定缓存管理器;或者cacheResolver指定获取解析器
    String cacheManager() default "";
    //
    String cacheResolver() default "";
    //指定符合条件的情况才缓存,例如condition="#id>0"
    String condition() default "";
    /*
    否定缓存,当unless指定条件为true,方法返回值就不会被缓存;
    可以获取到结果进行判断。 unless="#result==null"
    */
    String unless() default "";
    //是否使用异步模式
    boolean sync() default false;

标签:缓存,SpringBoot,default,指定,Cacheable,key,String
From: https://blog.51cto.com/u_15973676/6069282

相关文章