基于netcore的微服务——Hystrix(降级)(4)


版本为netcore2.1版本

一 、搭建项目

1.创建webapi项目
2.引入包

    <PackageReference Include="AspectCore.Core" Version="0.5.0" />
    <PackageReference Include="AspectCore.Extensions.DependencyInjection" Version="0.5.0" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
    <PackageReference Include="RuPeng.HystrixCore" Version="1.0.3" />

二、项目配置

1.Startup.cs


namespace hystrixTest
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //services.AddSingleton<Person>();
            RegisterServices(this.GetType().Assembly,services);
            return services.BuildAspectCoreServiceProvider();
        }
        //扫描asm程序中所有public类,对于类看看是否标注了HystrixCommand的方法,
        //如果有则AddSingleton到services
        private void RegisterServices(Assembly asm,IServiceCollection services)
        {
            foreach(Type type in asm.GetExportedTypes())
            {
                //判断type类中是否至少有一个方法含有HystrixCommandAttribute
                bool hasHystrxicCmd = type.GetMethods().Any(m => m.GetCustomAttribute(typeof(HystrixCommandAttribute))!=null);
                if(hasHystrxicCmd)
                {
                    services.AddSingleton(type);
                }
            }
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

2.Person.cs

namespace hystrixTest
{
    public class Person
    {
        [HystrixCommand(nameof(HelloFallBackAsync))]
        public virtual async Task<string> HelloAsyc(string name)
        {
            Console.WriteLine("hello" + name);
            String s = null;
            s.ToString();
            return "ok";
        }
        [HystrixCommand(nameof(HelloFallBackAsync2))]
        public virtual async Task<string> HelloFallBackAsync(string name)
        {
            Console.WriteLine("执行失败1" + name);
            String s = null;
            s.ToString();
            return "fail";
        }
        public async Task<string> HelloFallBackAsync2(string name)
        {
            Console.WriteLine("执行失败2" + name);
            return "fail2";
        }
        [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;
        }
    }
}

2.ValuesController.cs

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace hystrixTest.Controllers
{
   
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private Person person;
        public ValuesController( Person person)
        {
            this.person = person;
        }
        // GET api/values
        [HttpGet]
        public async Task<IEnumerable<string>> Get()
        {
            #region 非注入的方法
            //ProxyGeneratorBuilder proxyGeneratorBuilder = new ProxyGeneratorBuilder();
            //using (IProxyGenerator proxyGenerator = proxyGeneratorBuilder.Build())
            //{
            //    //AspectCore.DynamicProxy命名空间下得Person类
            //    Person p = proxyGenerator.CreateClassProxy<Person>();
            //    await p.HelloAsyc("张三");
            //}
            //return new string[] { "value1", "value2" };
            #endregion

            #region 通过注入得方法
            await person.HelloAsyc("张三");
            return new string[] { "value1", "value2" };
            #endregion
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

posted @   有诗亦有远方  阅读(20)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示