/// <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
联系客服