如何进行方法签名缓存?
我正在使用 .NET 和 C# 构建一个应用程序,我想通过使用属性/注释而不是方法中的显式代码来缓存一些结果。
我想要一个看起来有点像这样的方法签名:
[Cache, timeToLive=60]
String getName(string id, string location)
它应该根据输入生成哈希,并将其用作结果的密钥。 当然,会有一些配置文件告诉它如何实际放入内存缓存、本地字典或其他东西。
你知道这样的框架吗?
我什至对 Java 也感兴趣
I'm building an app in .NET and C#, and I'd like to cache some of the results by using attributes/annotations instead of explicit code in the method.
I'd like a method signature that looks a bit like this:
[Cache, timeToLive=60]
String getName(string id, string location)
It should make a hash based on the inputs, and use that as the key for the result.
Naturally, there'd be some config file telling it how to actually put in memcached, local dictionary or something.
Do you know of such a framework?
I'd even be interested in one for Java as well
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过 Microsoft Enterprise Library 中的 CacheHandler,您可以轻松实现此目的。
例如:
将使对该方法的所有调用缓存 30 分钟。所有调用都会根据输入数据和方法名称获取唯一的缓存键,因此如果您使用不同的输入调用该方法两次,则不会被缓存,但如果您在超时间隔内使用相同的输入调用它>1次,则该方法只执行一次。
我在微软的代码中添加了一些额外的功能:
我的修改版本如下所示:
这段代码最值得赞扬的是微软。我们只添加了请求级别的缓存等内容,而不是跨请求(比您想象的更有用),并修复了一些错误(例如,相同的 DateTime 对象序列化为不同的值)。
With CacheHandler in Microsoft Enterprise Library you can easily achieve this.
For instance:
would make all calls to that method cached for 30 minutes. All invocations gets a unique cache-key based on the input data and method name so if you call the method twice with different input it doesn't get cached but if you call it >1 times within the timout interval with the same input then the method only gets executed once.
I've added some extra features to Microsoft's code:
My modified version looks like this:
Microsoft deserves most credit for this code. We've only added stuff like caching at request level instead of across requests (more useful than you might think) and fixed some bugs (e.g. equal DateTime-objects serializing to different values).
要准确地执行您所描述的操作,即编写
并仅调用一次昂贵的调用,而无需使用其他代码包装该类 (fx
CacheHandlerc = new CacheHandler(new MyClass( ));
) 你需要研究一个面向方面的编程框架。这些通常通过重写字节码来工作,因此您需要在编译过程中添加另一个步骤 - 但您在此过程中获得了很多能力。 AOP 框架有很多,但 PostSharp for .NET 和 AspectJ 是最受欢迎的。您可以轻松地谷歌如何使用它们来添加您想要的缓存方面。To do exactly what you are describing, i.e. writing
and having only one invocation of the expensive call and without needing to wrap the class with some other code (f.x.
CacheHandler<MyClass> c = new CacheHandler<MyClass>(new MyClass());
) you need to look into an Aspect Oriented Programming framework. Those usually work by rewriting the byte-code, so you need to add another step to your compilation process - but you gain a lot of power in the process. There are many AOP-frameworks, but PostSharp for .NET and AspectJ are among the most popular. You can easily Google how to use those to add the caching-aspect you want.