Files
Yi.Admin/Yi.Framework.Net6/Yi.Framework.WebCore/AOP/RedisCacheAOP.cs
2023-01-06 16:32:43 +08:00

85 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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();//直接执行被拦截方法
}
}
}
}