Spring的@Cacheable在Spring Boot中的控制器中被调用时不起作用。

huangapple go评论65阅读模式
英文:

Spring's @Cacheable not working when called from the controller in Spring Boot

问题

你是否了解针对这种情况的Spring Boot特定解决方案?

我按照步骤实现了Spring的@Cacheable,但尽管我将代码简化为最简单的示例,它对我不起作用:

@Controller
public class TestController {

    @RequestMapping("/test")
    public String testView(){
        expensiveMethod();
        return "test";
    }

    @Cacheable("ones")
    public void expensiveMethod(){
       System.out.println("Cache is not being used");
    }
}

localhost:8080/test的每个请求都会打印这个字符串,不仅仅是第一个请求。

我已在我的主类上加上了@EnableCaching注解。

英文:

Do you know a Spring Boot specific soltution to this scenario?

I followed the steps to implement Spting's @Cacheable but it is not working for me although I reduced the code to the simplest example:

@Controller
public class TestController {

    @RequestMapping("/test")
    public String testView(){
        expensiveMethod();
        return "test";
    }


    @Cacheable("ones")
    public void expensiveMethod(){
       System.out.println("Cache is not being used");
    }

}

Every request to localhost:8080/test prints the string, not just the first one.

I annotated my main class with @EnableCaching

答案1

得分: 2

就像安德鲁所说,正确的问题应该是“在相同 中调用时”。

但是,由于建议帖子的回答过时了,并且有更好的方法适用于更新版本的Spring,我想分享我认为是最佳方法的做法:

  • 自动装配控制器并使用它来调用方法,而不是使用类上下文的 this

更新后的代码将如下所示:

@Controller
public class TestController {

    @Autowired TestController self;

    @RequestMapping("/test")
    public String testView(){
        self.expensiveMethod();
        return "test";
    }

    @Cacheable("ones")
    public void expensiveMethod(){
       System.out.println("现在正在使用缓存");
    }

}
英文:

Like Andrew said, the right question should be "when called in the same class".

But as the answers to the suggested post are really outdated and there are better approaches that are useful with newer versions of Spring, i would like to share what I think is the best approach:

  • Autowire the controller and use to call the method it instead of using the class context this.

The updated code would look like:

@Controller
public class TestController {


    @Autowired TestController self;

    @RequestMapping("/test")
    public String testView(){
        self.expensiveMethod();
        return "test";
    }


    @Cacheable("ones")
    public void expensiveMethod(){
       System.out.println("Cache is now being used");
    }

}

huangapple
  • 本文由 发表于 2020年9月18日 22:53:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63958101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定