2012-04-09 66 views
0

我想创建和指向缓存。我需要知道如何从一个方法调用创建一个缓存键并将其插入到缓存中并返回值。这部分是否有可用的解决方案?我不需要完整的缓存解决方案缓存服务调用

感谢

回答

0

我以前用过的RealProxy对于这种类型的功能。我在我的博客文章中展示了一些示例; Intercepting method invocations using RealProxy

缓存代理的一个简单示例,使用方法的哈希代码(确保两个具有相同参数的不同方法分别缓存)和参数。请注意,没有处理out-parameters,只有返回值。 (如果你想改变它,你需要改变_cache来保存一个包含返回值和输出参数的对象。)另外,这个实现没有表单线程安全性。

public class CachingProxy<T> : ProxyBase<T> where T : class { 
    private readonly IDictionary<Int32, Object> _cache = new Dictionary<Int32, Object>(); 

    public CachingProxy(T instance) 
     : base(instance) { 
    } 

    protected override IMethodReturnMessage InvokeMethodCall(IMethodCallMessage msg) { 
     var cacheKey = GetMethodCallHashCode(msg); 

     Object result; 
     if (_cache.TryGetValue(cacheKey, out result)) 
      return new ReturnMessage(result, msg.Args, msg.ArgCount, msg.LogicalCallContext, msg); 

     var returnMessage = base.InvokeMethodCall(msg); 

     if (returnMessage.Exception == null) 
      _cache[cacheKey] = returnMessage.ReturnValue; 

     return returnMessage; 
    } 

    protected virtual Int32 GetMethodCallHashCode(IMethodCallMessage msg) { 
     var hash = msg.MethodBase.GetHashCode(); 

     foreach(var arg in msg.InArgs) { 
      var argHash = (arg != null) ? arg.GetHashCode() : 0; 
      hash = ((hash << 5) + hash)^argHash; 
     } 

     return hash; 
    } 
} 
+0

我想你没有得到这个问题,我需要知道是否有解决方案来创建一个表示方法调用的缓存键(字符串)及其返回值。例如缓存SomeMethod(param1,param2),但寻找能够缓存具有任意数量参数的任何方法的通用解决方案 – Ehsan 2012-04-09 11:17:01

+0

我已经添加了一个基于ProxyBase 类的缓存调用的示例CachingProxy 。 – sisve 2012-04-09 14:01:12

+0

基于MSDN文档GetHashCode方法对于创建唯一的哈希键是不可靠的,如果我们说我们应该为每个类型实现此方法,我认为这也是一种不好的做法http://msdn.microsoft.com/zh-cn/ us/library/system.object.gethashcode.aspx第3行的备注部分 – Ehsan 2012-04-09 18:38:46