forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathBlogCacheAOP.cs
More file actions
54 lines (51 loc) · 1.81 KB
/
BlogCacheAOP.cs
File metadata and controls
54 lines (51 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using Blog.Core.Common;
using Blog.Core.Common.MemoryCache;
using Castle.DynamicProxy;
using System;
using System.Linq;
namespace Blog.Core.AOP
{
/// <summary>
/// 面向切面的缓存使用
/// </summary>
public class BlogCacheAOP : CacheAOPbase
{
//通过注入的方式,把缓存操作接口通过构造函数注入
private readonly ICaching _cache;
public BlogCacheAOP(ICaching cache)
{
_cache = cache;
}
//Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义
public override void Intercept(IInvocation invocation)
{
var method = invocation.MethodInvocationTarget ?? invocation.Method;
//对当前方法的特性验证
//如果需要验证
if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) is CachingAttribute qCachingAttribute)
{
//获取自定义缓存键
var cacheKey = CustomCacheKey(invocation);
//根据key获取相应的缓存值
var cacheValue = _cache.Get(cacheKey);
if (cacheValue != null)
{
//将当前获取到的缓存值,赋值给当前执行方法
invocation.ReturnValue = cacheValue;
return;
}
//去执行当前的方法
invocation.Proceed();
//存入缓存
if (!string.IsNullOrWhiteSpace(cacheKey))
{
_cache.Set(cacheKey, invocation.ReturnValue);
}
}
else
{
invocation.Proceed();//直接执行被拦截方法
}
}
}
}