LindDotNetCore~Polly组件对微服务场景的价值

2023-01-08,,,

回到目录

Polly是一个开源框架,在github上可以找到,被善友大哥收录,也是.App vNext的一员!

App vNext:https://github.com/App-vNext

GitHub:https://github.com/App-vNext/Polly

NanoFabric是一个开源的微服务架构,也是善友大哥推荐的:https://github.com/geffzhang/NanoFabric

对于NanoFabric来说,它集成了很多.net core开源项目,其中包括了Consul + .NET Core + Polly + Ocelot + Exceptionless + IdentityServer,你是否闻到了某种味道!

Polly给我们带来了什么

  1. 对http请求提供重试机制
  2. 对指定异常进行特殊的处理
  3. 提供了多种策略

程序中的使用

封装一个方法,对外提供一个委托的参数,把需要进行polly的代码段输入进来即可,对于http,数据库,网络通讯等非常必要,因为这些场景可能存在不稳定的因素!polly正好可以帮我们非常

友好的解决它,下面的代码主要实现了对所有异常的跟踪,然后每1秒重新执行一次,可以重试5次!

        /// <summary>
        /// polly重试机制
        /// </summary>
        private static HttpResponseMessage retryTwoTimesPolicy(Func<HttpResponseMessage> action)
        {
            var policy = Policy
                .Handle<Exception>()
                .WaitAndRetry(
                 5,
                 retryAttempt => TimeSpan.FromSeconds(Math.Pow(1, retryAttempt)),
                 (ex, timer, c, i) =>
                 {
                     logger.Logger_Info($"执行失败! 重试次数 {c}");
                     logger.Logger_Info($"异常来自 {ex.GetType().Name}");
                 });
            return policy.Execute(action);
        }

我们之前的httpHelper请求对象,也可以引入polly机制,全局进行控制!

        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="requestUri">服务地址</param>
        /// <param name="nv">参数键值</param>
        /// <returns></returns>
        public static HttpResponseMessage Get(
            string requestUri,
            NameValueCollection nv)
        {
            try
            {

                return retryTwoTimesPolicy(() =>
                {
                    var result = httpClient.GetAsync(GeneratorUri(requestUri, nv)).Result;
                    UnGZip(result);
                    return result;
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

自己开两个api进程,一个是对外提供服务,别一个作为主服务器,被其它进行访问,当它挂了之后,其实进行可以通过polly进行重试!

感谢各位的阅读!

微服务来了,但需要我们关注的点多了!

奋斗吧!

回到目录