Spring @Cacheable不缓存 [英] Spring @Cacheable not caching

查看:329
本文介绍了Spring @Cacheable不缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将Spring 3.2与EhCache 2.9结合使用。我注释了一个零参数方法,如下所示:

Using Spring 3.2 with EhCache 2.9. I've annotated a zero-parameter method as follows:

@Cacheable(value="myList", key="#result.method.name")
protected List<MyObject> getMyList() {
   //db query
   //return list of results
}

EhCache配置:

EhCache config:

<cache name="myList"
    statistics="true"
    maxEntriesLocalHeap="1"     
    timeToLiveSeconds="3600">
    <persistence strategy="none" />
</cache> 

我希望缓存数据库结果。由于此方法没有参数,因此我选择了方法名称作为缓存键。

I'd like the database results to be cached. Since this method has no parameters, I've chosen the method name to be the cache key.

当我对此进行测试时,每次调用方法时数据库都会被命中,我不确定为什么。有什么想法吗?

When I test this, the database is hit every method invocation and I'm not sure why. Any ideas?

更新

因此,在进行故障排除之后,我发现了一些有趣的东西。当前 getMyList 方法(在其上定义了缓存)在调用它的同一类中。该方法基本上调用DAO来查询列表。如果将 getMyList 移到另一个仅充当代理的类,然后更改原始调用程序以调用此新代理,则缓存起作用。我无法解释原因。

So after troubleshooting I found something interesting. Currently the getMyList method (on which the caching is defined) is in the same class that calls it. That method basically calls a DAO to query for the list. If I move getMyList outside to another class which just acts as a proxy, and then I change the original invoker to call this new proxy instead, then the caching works. I can't explain why. Any input?

推荐答案

想象一下您去了动物园。您进入入口一次并付款。之后,您可以参观狮子,老虎等……您不必每次都付费,因为您在进入时就付款了。如果您觉得无聊而又想去另一个动物园,则必须出去,转到下一个动物园,然后再付费。

Imagine you go to the Zoo. You go through the entrance once and pay your entry. Afterwards you can visit the Lions, the Tigers, and so on... You don't have to pay everytime because you did it when you entered. If you get bored and want to go to another Zoo, you have to go out, go to the next one, and pay again.

您的班级是动物园,您的方法是动物,缓存代理是入口。当有人调用您的课程时,它会一次通过缓存。当她进入并调用同一类的其他方法时,它不会再次通过缓存。

Your Class is the Zoo, your Methods are the Animals, and the Cache Proxy is the Entrance. When someone calls your class, it goes through the Cache once. When she is in, and calls another methods of the same class, it doesn't go through the Cache again. Only when you go out and in again, you go through the Cache.

只有当您一次又一次地进入并进入缓存时,您才可以使用一个讨厌的技巧来覆盖它,称为注入自己 >:

There is a nasty trick you can use to override this called inject yourself:

public class YourClass {
    @Autowired
    private YourClass instance;

    @Cacheable
    public String method1() {
          // now you go through the cache again
          return instance.method2();
    }

    @Cacheable
    public String method2() {
          return "2";
    }
}

这篇关于Spring @Cacheable不缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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