Skip to content

Instantly share code, notes, and snippets.

@EngRajabi
Last active May 6, 2021 12:36
Show Gist options
  • Save EngRajabi/591dabb16c82fc0de957a2ece9f067f6 to your computer and use it in GitHub Desktop.
Save EngRajabi/591dabb16c82fc0de957a2ece9f067f6 to your computer and use it in GitHub Desktop.
CacheInterceptor.cs
public class CacheInterceptor : IInterceptor
{
private readonly IDistributedCache _distributedCache;
public CacheInterceptor(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
public void Intercept(IInvocation invocation)
{
var cacheMethodAttribute = GetCacheMethodAttribute(invocation);
if (cacheMethodAttribute == null)
{
invocation.Proceed();
return;
}
var cacheDuration = ((CacheMethodAttribute)cacheMethodAttribute).SecondsToCache;
var cacheKey = GetCacheKey(invocation);
var cachedResult = _distributedCache.Get(cacheKey);
if (cachedResult != null)
{
//var lz4Decompress = cachedResult.Lz4Decompress();
var returnType = invocation.Method.ReturnType;
//var item = Activator.CreateInstance(returnType);
invocation.ReturnValue = cachedResult.DeserializeMessagePackLz4(returnType);
}
else
{
invocation.Proceed();
if (invocation.ReturnValue == null)
return;
var absoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(cacheDuration));
var cacheEntryOptions = new DistributedCacheEntryOptions
{
AbsoluteExpiration = absoluteExpiration
};
var byteArray = invocation.ReturnValue.SerializeMessagePackLz4();
// var lz4Compress = byteArray.Lz4Compress();
_distributedCache.Set(cacheKey, byteArray, cacheEntryOptions);
}
}
private static Attribute GetCacheMethodAttribute(IInvocation invocation)
{
var methodInfo = invocation.MethodInvocationTarget;
if (methodInfo == null)
methodInfo = invocation.Method;
return Attribute.GetCustomAttribute(methodInfo, typeof(CacheMethodAttribute), true);
}
private static string GetCacheKey(IInvocation invocation)
{
var byteArray = invocation.Arguments.ToByteArray();
var cacheKey = $"{invocation.TargetType.FullName}" +
$"{invocation.Method.Name}" +
$"{Encoding.UTF8.GetString(byteArray)}";
using var md5 = MD5.Create();
var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(cacheKey));
return Encoding.UTF8.GetString(hash).ToBase64Encode();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment