.net core编写转发服务(三) 接入Polly

在web服务里面,很常见出现各种问题,需要一些响应的策略,比如服务繁忙的时候,重试,或者重试等待

服务繁忙的时候根据策略即使处理

关于接入Polly我还是沿用之前的代码,继续迭代

Web Api用的是FastHttpApi

增加在过滤器里

    public class RetryAttribute: FilterAttribute
    {
        private int _count;

        public RetryAttribute(int count)
        {
            _count = count;
        }

        public override void Executed(ActionContext context)
        {
            try
            {
                var policy = Policy
                .Handle<Exception>()
                .Retry(_count, (ex, count) =>
                {
                    Console.WriteLine($"Retry Index:{count}, Exception:{ex.Message}");
                });

                policy.Execute(() =>
                {
                    base.Executed(context);

                    if (context.Exception != null)
                        throw context.Exception;
                });
            }
            catch(Exception ex)
            {

            }
        }
    }

在需要过滤的方法上面打上

        [Post(Route = "{url}")]
        [NoDataConvert]
        [Retry(5)]
        public async Task<ResponseModel> Service(string url,IHttpContext context)
        {
            //略略略
        }

我们测试一个不存在的服务

看见了重试了

响应信息如下

这明显不符合我们的要求,我们希望返回也是一个Model类型的

方便前端处理

修改一下过滤器的Executed

        public override void Executed(ActionContext context)
        {
            var requestTime = DateTime.Now;

            try
            {
                 //略略略
            }
            catch(Exception ex)
            {
                context.Result = new ResponseModel
                {
                    RequestTime = requestTime,
                    ResponseTime = DateTime.Now,
                    IsSuccessFul = false,
                    Data = null,
                    ErrorMessage = ex.Message
                };
                context.Exception = null;
            }
        }

再测试一下看看结果

ok~~~

我这里只是根据简单场景接入了Polly,同理可以在asp.net core里面加入,有兴趣的小伙伴可以看看

Polly参考Jeffcky的文章http://www.cnblogs.com/CreateMyself/p/7589397.html

还有很多用法,大家可以摸索一下

 

完整项目源码

https://github.com/htrlq/ForwardService

posted @ 2019-05-13 14:41  沉迷代码的萌新  阅读(405)  评论(0编辑  收藏  举报