有什么方法可以只为一种方法在 spring 中启用缓存吗?

Is there any way to enable caching in spring for only one method?

我有一个 spring 项目,我在其中实现了方法级别的缓存。现在我需要停止整个项目的缓存。我通过设置 false 的标志来阻止它。

现在我只想为一种方法启用缓存。有没有办法只为一种方法启用缓存?

@Cacheable(value = CacheHelper.APPLICATION_CACHE_NAME, key = "T(ca.sunlife.grs.core.cache.CacheHelper).generateApplicationCacheKey(T(ca.sunlife.grs.core.cache.CacheKey).CACHE_GET_MEMBER,#request.getClientId() + #request.getPlanId() + #request.getMemberNumber() +#request.getMemberIndicator())", unless = "#result== null")
public GetMemberMqResponse getMemberWithCache(GetMemberRequest request) throws Exception {
    GetMemberMqRequest mqRequest = getMemberDomainToMqMapper.toMqRequest(request);
    GrsLogger.info(this, "MQRequest is:" + mqRequest.getRequestString());
    return getMemberMqResponseParser.parseMqResponse(grsMqTransactionOrMockRunner.run(mqRequest));
}

你可以只把@Cacheable放在你想要缓存的方法上,把它从你不想缓存的方法上移除。

您可以使用 NoOpCacheManager and drive which CacheManager is enabled using Spring Profiles

public class NoOpCacheManager extends Object implements CacheManager

A basic, no operation CacheManager implementation suitable for disabling caching, typically used for backing cache declarations without an actual backing store. Will simply accept any items into the cache not actually storing them.

@Bean
public CacheManager cacheManager() {
    return new CaffeineCacheManager(); //Example implementation
}

@Bean
@Profile("noCaching")
@Primary
public CacheManager noOpCacheManager() {
    return new NoOpCacheManager();
}