打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
hytrix.net 熔断降级

 

/// <summary>    /// AOP 目标:use AspectCore ,在执行 HelloAsync 失败的时候自动执行 HelloFallBackAsync ,达到熔断降级    /// </summary>    class Program    {        static void Main(string[] args)        {            ProxyGeneratorBuilder proxyGeneratorBuilder = new ProxyGeneratorBuilder();            using (IProxyGenerator proxyGenerator = proxyGeneratorBuilder.Build())            {                Person p = proxyGenerator.CreateClassProxy<Person>();                Console.WriteLine(p.HelloAsync("Hello World").Result);                Console.WriteLine(p.Add(1, 2));            }        }    }

  

/// <summary>    /// 目标:在执行 HelloAsync 失败的时候自动执行 HelloFallBackAsync ,达到熔断降级    /// </summary>    public class Person    {        [HystrixCommand(nameof(HelloFallBackAsync))]        public virtual async Task<string> HelloAsync(string name)//需要是虚方法        {            Console.WriteLine("hello"   name);            //抛错            String s = null;            s.ToString();            return "ok";        }        public async Task<string> HelloFallBackAsync(string name)        {            Console.WriteLine("执行失败"   name);            return "fail";        }        [HystrixCommand(nameof(AddFall))]        public virtual int Add(int i, int j)        {            //抛错            String s = null;            //s.ToString();            return i   j;        }        public int AddFall(int i, int j)        {            return 0;        }    }    [AttributeUsage(AttributeTargets.Method)]    public class HystrixCommandAttribute : AbstractInterceptorAttribute    {        public string FallBackMethod { get; set; }        public HystrixCommandAttribute(string fallBackMethod)        {            this.FallBackMethod = fallBackMethod;        }        public override async Task Invoke(AspectContext context, AspectDelegate next)        {            try            {                await next(context);//执行被拦截的方法            }            catch (Exception ex)            {                /*                 * context.ServiceMethod 被拦截的方法                 * context.ServiceMethod.DeclaringType 被拦截的方法所在的类                 * context.Implementation 实际执行的对象                 * context.Parameters 方法参数值                 * 如果执行失败,则执行FallBackMethod                 */                var fallBackMethod = context.ServiceMethod.DeclaringType.GetMethod(this.FallBackMethod);                object fallBackResult = fallBackMethod.Invoke(context.Implementation, context.Parameters);                context.ReturnValue = fallBackResult;                await Task.FromResult(0);            }        }    }

  

来源:https://www.icode9.com/content-4-639251.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
(6).NET CORE微服务 Micro
C# task 传多个参数
C# Left, Right and Mid函数
委托小例
C#函数(构造函数)的重载
unknown
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服