/// <summary> /// 拦截被特性标记的方法 /// </summary> /// <param name="invocation"></param> public void Intercept(CacheAttribute attribute, IInvocation invocation) { if (attribute == null) { invocation.Proceed(); } else { ProgressCaching(invocation, attribute); } }
/// <summary> /// 操作缓存 /// </summary> /// <param name="invocation"></param> private void ProgressCaching(IInvocation invocation, CacheAttribute mapCacheAttribute) { var typeName = invocation.TargetType.Name; var methodName = invocation.Method.Name; Type methodReturnType = invocation.Method.ReturnType; var methodArguments = ParseArgumentsToPartOfCacheKey(invocation.Arguments); var cacheKey = BuildCacheKey(typeName, methodName, methodArguments, mapCacheAttribute.prefixs); var cacheValue = _cacheClient.StringGet(cacheKey); if (cacheValue != null) { //基元类型和string类型不需要序列化 if (methodReturnType.IsPrimitive || methodReturnType.Name == "String") { invocation.ReturnValue = cacheKey; } else { var contractResolver = new JsonContractResolver(); JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = contractResolver }; invocation.ReturnValue = JsonConvert.DeserializeObject(cacheValue, methodReturnType, jsonSerializerSettings); } return; } invocation.Proceed(); if (!string.IsNullOrWhiteSpace(cacheKey)) { _cacheClient.StringSet(cacheKey, invocation.ReturnValue); } }