根据配置为服务中的特定方法启用/禁用缓存 [英] Enable/Disable Caching for specific methods in a service based on configuration

查看:79
本文介绍了根据配置为服务中的特定方法启用/禁用缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用Spring的缓存抽象为我们的服务添加缓存行为.

We are using Spring's Caching abstraction to add caching behaviour to our services.

默认情况下,@ Enablecaching注释会启用/禁用整个服务的缓存.

By default, @Enablecaching annotation either enables/disables caching for entire service.

@Cacheable批注已在所有方法上使用.

The @Cacheable annotation has been used on all methods.

但是,现在我们要为某些端点/方法启用缓存,并为其他端点禁用缓存

But, now we want to enable caching for some endpoints/methods and disable caching for other endpoints

有没有一种方法可以通过删除服务中添加的注释来实现,例如拦截器/过滤器否决基于配置的某些方法的缓存行为.

Is there a way to achieve that with removing the added annotations in the service something like an Interceptor/Filter vetoing the caching behaviour for certain methods based on configuration.

推荐答案

为此可以解决的一个问题是,您可以基于参数使方法成为缓存的条件.缓存批注通过条件参数支持这种功能,该条件参数采用SpEL表达式,该表达式被评估为true或false.

One work around for this You can make your method conditional for cache on the base of parameter. The cache annotations support such functionality through the condition parameter which takes a SpEL expression that is evaluated to either true or false.

@Cacheable(cacheNames="book", condition="#cached == false")
public Book findBook(boolean cached)

如文档中所述. https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html

这篇关于根据配置为服务中的特定方法启用/禁用缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆