增加缓存AOP切面

This commit is contained in:
JINBO
2023-01-06 16:32:43 +08:00
parent 1ed37897d5
commit 898be6c733
11 changed files with 332 additions and 3 deletions

View File

@@ -0,0 +1,90 @@
using Castle.DynamicProxy;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Yi.Framework.Common.Base;
using Yi.Framework.Common.Helper;
namespace Yi.Framework.WebCore.AOP
{
public abstract class CacheAOPbase : IInterceptor
{
/// <summary>
/// AOP的拦截方法
/// </summary>
/// <param name="invocation"></param>
public abstract void Intercept(IInvocation invocation);
/// <summary>
/// 自定义缓存的key
/// </summary>
/// <param name="invocation"></param>
/// <returns></returns>
protected string CustomCacheKey(IInvocation invocation)
{
var typeName = invocation.TargetType.Name;
var methodName = invocation.Method.Name;
var methodArguments = invocation.Arguments.Select(GetArgumentValue).Take(3).ToList();//获取参数列表,最多三个
string key = $"{typeName}:{methodName}:";
foreach (var param in methodArguments)
{
key = $"{key}{param}:";
}
return key.TrimEnd(':');
}
/// <summary>
/// object 转 string
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
protected static string GetArgumentValue(object arg)
{
if (arg is DateTime)
return ((DateTime)arg).ToString("yyyyMMddHHmmss");
if (!arg.IsNotNull())
return arg.TryStringNull();
if (arg != null)
{
if (arg is Expression)
{
var obj = arg as Expression;
var result = Resolve(obj);
return MD5Helper.MD5Encrypt16(result);
}
else if (arg.GetType().IsClass)
{
return MD5Helper.MD5Encrypt16(JsonConvert.SerializeObject(arg));
}
return $"value:{arg.TryStringNull()}";
}
return string.Empty;
}
private static string Resolve(Expression expression)
{
ExpressionContext expContext = new ExpressionContext();
expContext.Resolve(expression, ResolveExpressType.WhereSingle);
var value = expContext.Result.GetString();
var pars = expContext.Parameters;
pars.ForEach(s =>
{
value = value.Replace(s.ParameterName, s.Value.TryStringNull());
});
return value;
}
}
}

View File

@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Yi.Framework.WebCore.AOP
{
public class MemoryCacheAOP : CacheAOPbase
{
private CacheInvoker _cache;
public MemoryCacheAOP(CacheInvoker cache)
{
_cache = cache;
}
public override void Intercept(IInvocation invocation)
{
var method = invocation.MethodInvocationTarget ?? invocation.Method;
var CachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute));
if (CachingAttribute is CachingAttribute qCachingAttribute)
{
//获取自定义缓存键
var cacheKey = CustomCacheKey(invocation);
//根据key获取相应的缓存值
var cacheValue = _cache.Get<string>(cacheKey);
if (cacheValue != null)
{
//将当前获取到的缓存值,赋值给当前执行方法
invocation.ReturnValue = cacheValue;
return;
}
//去执行当前的方法
invocation.Proceed();
//存入缓存
if (!string.IsNullOrWhiteSpace(cacheKey))
{
_cache.Set(cacheKey, invocation.ReturnValue, TimeSpan.FromMinutes(qCachingAttribute.AbsoluteExpiration));
}
}
else
{
invocation.Proceed();//直接执行被拦截方法
}
}
}
}

View File

@@ -0,0 +1,84 @@
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();//直接执行被拦截方法
}
}
}
}

View File

@@ -92,6 +92,10 @@ namespace Yi.Framework.WebCore.AspNetCoreExtensions
{
//entityInfo.SetValue(new Guid(httpcontext.Request.Headers["TenantId"].ToString()));
}
if (entityInfo.PropertyName == "CreateTime")
{
entityInfo.SetValue(DateTime.Now);
}
break;
case DataFilterType.UpdateByObject:
if (entityInfo.PropertyName == "ModifyTime")

View File

@@ -16,7 +16,9 @@ using Yi.Framework.Interface;
using Yi.Framework.Job;
using Yi.Framework.Repository;
using Yi.Framework.Service;
using Yi.Framework.WebCore.AOP;
using Yi.Framework.WebCore.AutoFacExtend;
using Yi.Framework.WebCore.CommonExtend;
using Yi.Framework.WebCore.Impl;
using Module = Autofac.Module;
@@ -43,6 +45,17 @@ namespace Yi.Framework.WebCore.AutoFacExtend
containerBuilder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
var cacheType = new List<Type>();
if (Appsettings.appBool("RedisCacheAOP_Enabled"))
{
containerBuilder.RegisterType<RedisCacheAOP>();
cacheType.Add(typeof(RedisCacheAOP));
}
if (Appsettings.appBool("MemoryCacheAOP_Enabled"))
{
containerBuilder.RegisterType<MemoryCacheAOP>();
cacheType.Add(typeof(MemoryCacheAOP));
}
//containerBuilder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
//containerBuilder.RegisterGeneric(typeof(BaseService<>)).As(typeof(IBaseService<>)).InstancePerLifetimeScope();
///反射注入服务层及接口层
@@ -50,7 +63,8 @@ namespace Yi.Framework.WebCore.AutoFacExtend
containerBuilder.RegisterAssemblyTypes(assemblysServices).PropertiesAutowired(new AutowiredPropertySelector())
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.EnableInterfaceInterceptors();
.EnableInterfaceInterceptors()
.InterceptedBy(cacheType.ToArray());
//开启工作单元拦截
//.InterceptedBy(typeof(UnitOfWorkInterceptor));