基于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)
        {
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有诗亦有远方

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值