1. 程式人生 > >微服務入門06AspectCore Aop

微服務入門06AspectCore Aop

tint tel exc command ole asp method tco res

基本的使用方式可以去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