namespace CloudGaming.Core.FreeRedis.Aop.Cache;
///
/// 缓存AOP
///
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class FreeRedisCacheableAttribute : FreeRedisBaseCacheAttribute
{
///
/// 缓存时长 (秒) 默认存储 10s 如果0代表永久
///
///
public long CacheDuration { get; set; } = 10;
///
///
///
///
public override void OnEntry(MethodContext context)
{
if (!UseFreeRedis)
{
GetMemoryCache(context);
return;
}
GetRedisCache(context);
}
public override void OnException(MethodContext context)
{
}
public override void OnSuccess(MethodContext context)
{
switch (context.ReturnValue)
{
case null:
case ICollection { Count: 0 }:
return;
default:
CreateCache(context, context.ReturnValue);
break;
}
}
public override void OnExit(MethodContext context)
{
}
///
/// 获取 MemoryCache 缓存
///
///
private void GetMemoryCache(MethodContext context)
{
var key = GetCacheKey(context);
var memoryCache = GetService(context);
if (memoryCache is null) return;
var value = memoryCache.Get(key);
if (value is null) return;
context.ReplaceReturnValue(this, value);
}
///
/// 获取 RedisCache 缓存
///
///
private void GetRedisCache(MethodContext context)
{
var key = GetCacheKey(context);
var redisCache = GetDatabase(context);
var value = redisCache.Get(key);
var val = string.IsNullOrWhiteSpace(value)
? null
: JsonConvert.DeserializeObject(value, context.RealReturnType);
if (val == null) return;
context.ReplaceReturnValue(this, val);
}
///
/// 创建缓存
///
///
///
private void CreateCache(MethodContext MethodContext, object result)
{
if (!UseFreeRedis)
{
CreateMemoryCache(MethodContext, result);
return;
}
CreateRedisCache(MethodContext, result);
}
///
/// 创建内存缓存
///
///
///
private void CreateMemoryCache(MethodContext context, object result)
{
var memoryCache = GetService(context);
var key = GetCacheKey(context);
if (CacheDuration <= 0)
{
memoryCache.Set(key, result);
}
else
{
memoryCache.Set(key, result, TimeSpan.FromSeconds(CacheDuration));
}
}
///
/// 创建Redis缓存
///
///
///
private void CreateRedisCache(MethodContext context, object result)
{
var redisCache = GetDatabase(context);
var key = GetCacheKey(context);
if (CacheDuration <= 0)
{
redisCache.Set(key, JsonConvert.SerializeObject(result));
}
else
{
redisCache.Set(key, JsonConvert.SerializeObject(result), TimeSpan.FromSeconds(CacheDuration));
}
}
}