public CacheProxy(ICacheAPI cacheApi, CacheMode cacheMode, CacheStatistics cacheStatistics) { this.cacheApi = cacheApi; this.cacheMode = cacheMode; this.cacheStatistics = cacheStatistics; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { CacheMode cacheMode = GetCacheMode(input.MethodBase); ICacheAPI cacheAPI = ChooseCacheAPI(cacheMode); if (cacheAPI == null) { logger.Error("No cache used"); return(getNext()(input, getNext)); } string cacheImplName = cacheAPI.GetType().Name; cacheAPI = new CacheProxy(cacheAPI, cacheMode, cacheStatistics); CacheType cacheType = GetCacheType(input.MethodBase); string cacheGroup = GetCacheGroup(input.MethodBase); string cacheKey = CreateCacheKey(input.MethodBase, input.Arguments); logger.Info(string.Format("Choose cache api as {0}, cacheGroup={1}, cacheKey={2}", cacheImplName, cacheGroup, cacheKey)); if (cacheMode.Equals(CacheMode.REMOTE) && cacheStatistics.IsError(cacheMode, cacheGroup)) { logger.Error("Remote cache error occured too many, skip cache, get data from DB."); return(getNext()(input, getNext)); } if (CacheType.FETCH.Equals(cacheType)) { object obj = null; try { obj = cacheAPI.Get(cacheGroup, cacheKey); } catch (Exception ex) { logger.Error("get cache failed, cachetype=" + cacheType, ex); return(getNext()(input, getNext)); } if (obj != null) { logger.Info("Hitting cache, cacheGroup=" + cacheGroup + ", cacheKey=" + cacheKey); cacheStatistics.AddHitCount(cacheMode, cacheGroup); return(input.CreateMethodReturn(obj, null)); } else { cacheStatistics.AddUnhitCount(cacheMode, cacheGroup); IMethodReturn methodReturn = getNext()(input, getNext); if (methodReturn.Exception == null && methodReturn.ReturnValue != null) { cacheAPI.Add(cacheGroup, cacheKey, methodReturn.ReturnValue); logger.Info("Adding into cache, cacheGroup=" + cacheGroup + ", cacheKey=" + cacheKey); } return(methodReturn); } } else if (CacheType.CLEAR.Equals(cacheType)) { IMethodReturn methodReturn = getNext()(input, getNext); cacheAPI.Remove(cacheGroup, cacheKey); return(methodReturn); } else if (CacheType.UPDATE.Equals(cacheType)) { object cacheValue = GetCacheValue(input.Arguments); if (cacheValue != null) { cacheAPI.Update(cacheGroup, cacheKey, cacheValue); logger.Info("Update cache, cacheGroup=" + cacheGroup + ", cacheKey=" + cacheKey); } return(getNext()(input, getNext)); } else { logger.Error("Invalid cache type, cachetype=" + cacheType); return(getNext()(input, getNext)); } }