mirror of
https://gitee.com/ccnetcore/Yi
synced 2026-03-12 04:29:28 +08:00
85 lines
3.0 KiB
C#
85 lines
3.0 KiB
C#
using Castle.DynamicProxy;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
using Yi.Framework.Core.Cache;
|
||
using Yi.Framework.Common.Attribute;
|
||
|
||
namespace Yi.Framework.WebCore.AOP
|
||
{
|
||
public class RedisCacheAOP : CacheAOPbase
|
||
{
|
||
private CacheInvoker _cacheDb;
|
||
public RedisCacheAOP(CacheInvoker cacheInvoker)
|
||
{
|
||
_cacheDb = cacheInvoker;
|
||
}
|
||
|
||
public override void Intercept(IInvocation invocation)
|
||
{
|
||
var method = invocation.MethodInvocationTarget ?? invocation.Method;
|
||
if (method.ReturnType == typeof(void) || method.ReturnType == typeof(Task))
|
||
{
|
||
invocation.Proceed();
|
||
return;
|
||
}
|
||
|
||
var qCachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute;
|
||
|
||
if (qCachingAttribute != null)
|
||
{
|
||
//获取自定义缓存键
|
||
var cacheKey = CustomCacheKey(invocation);
|
||
//注意是 string 类型,方法GetValue
|
||
var cacheValue = _cacheDb.Get<string>(cacheKey);
|
||
if (cacheValue != null)
|
||
{
|
||
//将当前获取到的缓存值,赋值给当前执行方法
|
||
Type returnType;
|
||
if (typeof(Task).IsAssignableFrom(method.ReturnType))
|
||
{
|
||
returnType = method.ReturnType.GenericTypeArguments.FirstOrDefault();
|
||
}
|
||
else
|
||
{
|
||
returnType = method.ReturnType;
|
||
}
|
||
|
||
dynamic _result = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, returnType);
|
||
invocation.ReturnValue = (typeof(Task).IsAssignableFrom(method.ReturnType)) ? Task.FromResult(_result) : _result;
|
||
return;
|
||
}
|
||
//去执行当前的方法
|
||
invocation.Proceed();
|
||
|
||
//存入缓存
|
||
if (!string.IsNullOrWhiteSpace(cacheKey))
|
||
{
|
||
object response;
|
||
|
||
//Type type = invocation.ReturnValue?.GetType();
|
||
var type = invocation.Method.ReturnType;
|
||
if (typeof(Task).IsAssignableFrom(type))
|
||
{
|
||
var resultProperty = type.GetProperty("Result");
|
||
response = resultProperty.GetValue(invocation.ReturnValue);
|
||
}
|
||
else
|
||
{
|
||
response = invocation.ReturnValue;
|
||
}
|
||
if (response == null) response = string.Empty;
|
||
|
||
_cacheDb.Set(cacheKey, response, TimeSpan.FromMinutes(qCachingAttribute.AbsoluteExpiration));
|
||
}
|
||
}
|
||
else
|
||
{
|
||
invocation.Proceed();//直接执行被拦截方法
|
||
}
|
||
}
|
||
}
|
||
}
|