春季缓存仅在某些情况下有效 [英] Spring caching works only sometimes

查看:83
本文介绍了春季缓存仅在某些情况下有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring控制器,想缓存响应.当我将@Cacheable注释从getBooks移到doGetBooks方法时,缓存将停止.一旦将其移回getBooks方法,缓存将再次起作用.为什么会这样,我该如何解决?

I have a Spring controller and want to cache the response. When I move the @Cacheable annotation from the getBooks to the doGetBooks method, the caching will stop. Once I move it back to the getBooks method caching works again. Why is that and how can I fix it?

这将缓存公共方法响应

@GetMapping
@Cacheable(value = "cache", key = "{ #root.methodName }")
public Books getBooks(@RequestHeader(value = "user-agent", required = false) String userAgent) throws Exception {
     if(valid) {
          return this.doGetBooks();
     }
     throw new Exception();
}


public Books doGetBooks() throws Exception{
    ...

这将永远不会缓存私有方法响应

This will never cache the private method response

@GetMapping
public Books getBooks(@RequestHeader(value = "user-agent", required = false) String userAgent) throws Exception {
     if(valid) {
          return this.getBooks();
     }
     throw new Exception();
}


@Cacheable(value = "cache", key = "{ #root.methodName }")
public Books doGetBooks() throws Exception{
    ...

推荐答案

问题:您正在同一类中调用doGetBooks(),并且Spring缓存需要AOP代理才能调用被调用的方法.

Problem: You are calling doGetBooks() within the same class, and Spring cache requires an AOP proxy to the called method.

这是一个很好的讨论,描述了为什么Spring AOP无法拦截其他类方法调用的方法:

This is a good discussion describing why Spring AOP can not intercept methods called by other class methods: AOP calling methods within methods

至少有三种解决方法:

  1. 重构代码:将doGetBooks()移至另一个@Component,然后使用该(注入的)bean(refactoredBean.doGetBooks())调用该方法
  2. 创建对调用调用的服务的自引用(通过@Autowired私有MyService myservice并调用myservice.doGetBooks().
  3. 使用ApplicationContext强制转换服务bean,并在该bean上调用方法.

一旦调用了Spring Cache可以拦截(通过AOP)的方法,那么@Cacheable()批注就会触发.

Once you invoke a method that Spring Cache can intercept (via AOP), then the @Cacheable() annotation should trigger.

这篇关于春季缓存仅在某些情况下有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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