Exemplo n.º 1
0
        //Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义
        public override void Intercept(IInvocation invocation)
        {
            var method = invocation.MethodInvocationTarget ?? invocation.Method;

            //对当前方法的特性验证
            //如果需要验证
            if (method.IsDefined(typeof(CachingAttribute), true))
            {
                var attribute = (CachingAttribute)method.GetCustomAttribute(typeof(CachingAttribute), true);
                //获取自定义缓存键
                var cacheKey = CustomCacheKey(invocation);

                //根据key获取相应的缓存值
                var cacheValue = _cache.Get <object>(cacheKey);

                if (cacheValue != null)
                {
                    //将当前获取到的缓存值,赋值给当前执行方法
                    invocation.ReturnValue = cacheValue;
                    return;
                } //去执行当前的方法
                invocation.Proceed();
                //存入缓存
                if (!string.IsNullOrWhiteSpace(cacheKey))
                {
                    _cache.Set(cacheKey, invocation.ReturnValue, attribute.AbsoluteExpiration);
                }
            }
            else
            {
                invocation.Proceed();//直接执行被拦截方法
            }
        }
Exemplo n.º 2
0
        public override void Intercept(IInvocation invocation)
        {
            var method = invocation.MethodInvocationTarget ?? invocation.Method;

            // 对当前方法的特性判断
            if (method.GetCustomAttribute(typeof(CacheAttribute)) is CacheAttribute cacheAttribute)
            {
                // 获取自定义缓存键
                var cacheKey = CustomCacheKey(invocation);
                // 根据key获取相应的值
                var cacheValue = _memoryCaching.Get(cacheKey);
                if (cacheValue != null)
                {
                    // 将当前获取到的缓存值,赋值给当前执行方法
                    invocation.ReturnValue = cacheValue;
                    return;
                }

                // 去执行当前的方法
                invocation.Proceed();

                //存入缓存
                if (!cacheKey.IsNullOrEmpty())
                {
                    _memoryCaching.Set(cacheKey, invocation.ReturnValue, cacheAttribute.AbsoluteExpiration);
                }
            }
            else
            {
                invocation.Proceed(); // 直接执行被拦截方法
            }
        }