我可以在 Spring 中将方法注释为可缓存吗?

发布于 2024-09-19 02:37:38 字数 654 浏览 3 评论 0原文

我想使用一个注释将方法调用的结果标记为可缓存。当提供时,它将使用缓存提供程序来缓存给定输入的输出。例如:

@Cacheable
public Bar doExpensiveCalculation(Foo foo) {
    Bar bar = jiggeryPokeryWith(foo);
    return bar;
}

...

Foo foo1 = new Foo(...);
Foo foo2 = new Foo(...);

Bar bar1 = doExpensiveCalculation(foo1);
Bar bar2 = doExpensiveCalculation(foo2);
Bar bar3 = doExpensiveCalculation(foo1);
// no calculation done on previous line, cached result == bar1

在这个例子的最后,缓存将包含

{doExpensiveCalculation(foo1) -> bar1, 
 doExpensiveCalculation(foo2) -> bar2}

我确信使用 AOP 是可能的。由于 Spring 既支持 AOP 又支持缓存,因此它似乎非常适合这个用例。

存在这样的功能吗?

I would like to use an annotation that marked the result of a method call as cacheable. When provided it would use a caching provider to cache the output for the given input. For example:

@Cacheable
public Bar doExpensiveCalculation(Foo foo) {
    Bar bar = jiggeryPokeryWith(foo);
    return bar;
}

...

Foo foo1 = new Foo(...);
Foo foo2 = new Foo(...);

Bar bar1 = doExpensiveCalculation(foo1);
Bar bar2 = doExpensiveCalculation(foo2);
Bar bar3 = doExpensiveCalculation(foo1);
// no calculation done on previous line, cached result == bar1

At the end of this example the cache would contain

{doExpensiveCalculation(foo1) -> bar1, 
 doExpensiveCalculation(foo2) -> bar2}

I am sure this is possible using AOP. As Spring does both AOP and caching, it seems it would be a natural fit for this use case.

Does such a feature exist?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

西瑶 2024-09-26 02:37:38

此模块有您想要的内容。 (但实际上实现起来非常简单)

This module has what you want. (But it is actually pretty straightforward to implement)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文