@cacheable属性含义
时间: 2023-08-07 16:08:38 浏览: 46
@Cacheable 是Spring框架中的注解,用于将方法的返回值缓存起来,当下次请求时直接从缓存中获取结果,而不用再执行一遍方法。@Cacheable 注解可以应用在方法上,也可以应用在类上。
@Cacheable 注解有一些常用的属性,下面是这些属性的含义:
1. value:缓存的名称,可以指定一个或多个缓存,多个缓存之间用逗号隔开。
2. key:缓存的键值,可以使用SpEL表达式,例如:`key="#id"`。
3. condition:缓存的条件,满足条件的才会被缓存,可以使用SpEL表达式,例如:`condition="#id>0"`。
4. unless:缓存的排除条件,满足条件的不会被缓存,可以使用SpEL表达式,例如:`unless="#result==null"`。
5. sync:是否使用异步模式,如果为 true,则表示异步执行方法,缓存不会立即返回,而是等待方法执行完成后再返回,默认为 false。
其中,value 属性是必须的,其他属性都是可选的。需要注意的是,当指定多个缓存时,如果其中一个缓存失效,则所有缓存都会失效。因此,在使用 @Cacheable 注解时,需要谨慎配置缓存的名称和键值,以确保缓存的准确性和有效性。
相关问题
@Cacheable的属性unless
@Cacheable的属性unless是用来指定一个SpEL表达式,表示在方法执行后检查返回结果是否满足条件,如果满足条件则不会将结果缓存起来。在上述引用和引用的例子中,属性unless的值为"#result == null",表示如果方法返回的结果为空(null),则不会将结果缓存起来。换句话说,只有当方法返回的结果不为空时,才会将结果缓存。这样可以避免将无效的数据缓存起来,节省了缓存空间。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用](https://download.csdn.net/download/weixin_38611877/12781025)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [Spring Cache的@Cacheable注解的condition属性与unless属性细节问题;Redis每日一坑](https://blog.csdn.net/qq_45839663/article/details/127208978)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [Spring Cache的@Cacheable注解的condition属性与unless属性细节问题](https://blog.csdn.net/m0_56265851/article/details/126389539)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
@Cacheable 注解有 expire 属性
`@Cacheable` 注解是 Spring Framework 中用于实现缓存的注解。它可以应用在方法上,表示该方法的返回值将被缓存起来以提高访问效率。`@Cacheable` 注解有一个 `value` 属性,用于指定缓存使用的名称。此外,`@Cacheable` 还有一个 `key` 属性,用于指定缓存的 key 值。
`@Cacheable` 注解还有一个可选的 `expire` 属性,用于指定缓存的过期时间。默认情况下,缓存项会永久保存,但是可以使用 `expire` 属性来指定缓存项的过期时间。`expire` 属性的值是一个以秒为单位的整数,表示缓存项的过期时间。例如,`@Cacheable(value = "myCache", key = "#id", expire = 60)` 表示缓存名称为 "myCache",缓存 key 为 `#id` 的缓存项的过期时间为 60 秒。