码迷,mamicode.com
首页 > Web开发 > 详细

微服务入门06AspectCore Aop

时间:2018-09-22 18:21:48      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:try   his   context   res   override   llb   hello   orb   使用   

基本的使用方式可以去GitHub上看,这里只介绍如和与polly联合起来使用,要达到这样一个目的

HelloAsync有可能会抛异常,若执行失败就降级执行HelloFallbackAsync 方法

注意 方法标注[HystrixCommand]并且是 virtual 标注
创建拦截器

[AttributeUsage(AttributeTargets.Method)]
    public class HystrixCommandAttribute:AbstractInterceptorAttribute
    {
        private string fallbackMethod;
        public HystrixCommandAttribute(string fallbackMethod)
        {
            this.fallbackMethod = fallbackMethod;
        }
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            try
            {
                await next(context);
            }
            catch (Exception)
            {
                Console.WriteLine("出错");
                //1获得降级方法
               var fallback = context.Implementation.GetType().GetMethod(fallbackMethod);
                //2调用降级方法
                var returnVal =fallback.Invoke(context.Implementation, context.Parameters);
                //3把降级方法的返回直返回
                context.ReturnValue = returnVal;
                //throw;
            }
        }
    }

编写需要被代理拦截的类

public class Person{
 
        [HystrixCommand(nameof(HelloFallbackAsync))]
        public virtual async Task<string> HelloAsync(string name){
            Console.WriteLine("name" +name);
            throw new Exception("i am ex");
            return "ok";
        }
        public virtual async Task<string> HelloFallbackAsync(string name){
            Console.WriteLine("执行失败" +name);
            return "fail";
        }

    }

创建

    ProxyGeneratorBuilder proxyGeneratorBuilder = new ProxyGeneratorBuilder();
    using (IProxyGenerator proxyGenerator = proxyGeneratorBuilder.Build())
    {
        var p = proxyGenerator.CreateClassProxy<Person>();
        var re = p.HelloAsync("rup").Result;
        Console.WriteLine(re);
    }

微服务入门06AspectCore Aop

标签:try   his   context   res   override   llb   hello   orb   使用   

原文地址:https://www.cnblogs.com/Amayer/p/9690447.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!