• 微服务入门06AspectCore Aop


    基本的使用方式可以去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);
        }
    
  • 相关阅读:
    CodeForces 383C-dfs序-线段树
    poj-3321-dfs序-线段树-邻接表
    poj2528-Mayor's posters-线段树离散化、基础
    hdu3333-Turing Tree-线段树+离线+离散化
    poj 1151-atlantis-线段树扫描线求面积并
    Changes favor the connective minds.
    HDU 4800/zoj 3735 Josephina and RPG 2013 长沙现场赛J题
    HDU 1203 I NEED A OFFER! 01背包
    hdu 1175 连连看 DFS
    Codeforces Round #208 (Div. 2) 358D Dima and Hares
  • 原文地址:https://www.cnblogs.com/Amayer/p/9690447.html
Copyright © 2020-2023  润新知