BaseRequest

public class BaseRequest
{public int TimeOut { get; set; } = 300;public Method Method { get; set; }public string? Url { get; set; }public string ContentType { get; set; } = "application/json";public object? Parameter { get; set; }
}
using System.Net;
using System.Text.Json;
using Newtonsoft.Json;
using Polly;
using RestSharp;
using JsonSerializer = System.Text.Json.JsonSerializer;namespace RestsharpDemo;public class RestSharpService : IHttpService
{private readonly RestClient _client;private int _maxRetryAttempts = 2;//重试次数private double _pauseBetweenFailuresSecond = 1d;  //失败后的暂停多久重试 单位spublic RestSharpService(RestClient restClient){_client = restClient;}public async Task<string?> ExecuteAsync(BaseRequest baseRequest){try{if (string.IsNullOrEmpty(baseRequest.Url)){return "Url is Empty";}var url = new Uri(baseRequest.Url);var request = new RestRequest(url, baseRequest.Method);request.AddHeader("Content-Type", baseRequest.ContentType);var param = JsonConvert.SerializeObject(baseRequest.Parameter);if (baseRequest.Parameter != null){request.AddParameter("application/json", param, ParameterType.RequestBody);}var response = await RestResponseWithPolicyAsync(request);if (response.StatusCode == HttpStatusCode.OK){return response.Content;}if (response.ErrorException != null){return response.ErrorException.Message;}return response.ErrorMessage;}catch (Exception ex){return ex.Message;}}/// <summary>/// 使用Policy执行http请求/// </summary>/// <param name="restRequest"></param>/// <returns></returns>private Task<RestResponse> RestResponseWithPolicyAsync(RestRequest restRequest){var retryPolicy = Policy.HandleResult<RestResponse>(x => !x.IsSuccessful).WaitAndRetryAsync(_maxRetryAttempts, x => TimeSpan.FromSeconds(_pauseBetweenFailuresSecond), (restResponse, timeSpan, retryCount, context) =>{Console.WriteLine($"The request failed. HttpStatusCode={restResponse.Result.StatusCode}. " +$"\nWaiting {timeSpan.TotalSeconds} seconds before retry. Number attempt {retryCount}." +$"\n Uri={restResponse.Result.ResponseUri}; " +$"\nRequestResponse={restResponse.Result.Content}"+ $"\nErrorMessage={restResponse.Result.ErrorMessage}");});var circuitBreakerPolicy = Policy.HandleResult<RestResponse>(x => x.StatusCode == HttpStatusCode.ServiceUnavailable).CircuitBreakerAsync(1, TimeSpan.FromSeconds(60), onBreak: (restResponse, timespan, context) =>{Console.WriteLine($"Circuit went into a fault state. Reason: {restResponse.Result.Content}");},onReset: (context) =>{Console.WriteLine($"Circuit left the fault state.");});return retryPolicy.WrapAsync(circuitBreakerPolicy).ExecuteAsync(() => _client.ExecuteAsync(restRequest));}public async Task<TResponse?> GetAsync<TResponse>(string url) where TResponse : class{var text = await ExecuteAsync(new BaseRequest(){Url = url,Method = Method.Get,});return (typeof(TResponse) == typeof(string)) ? ((text as TResponse)) : (ToJsonModel<TResponse>(text));}public async Task<TResponse?> PostAsync<TResponse>(string url, object param) where TResponse : class{var text = await ExecuteAsync(new BaseRequest(){Url = url,Method = Method.Post,Parameter = param});return (typeof(TResponse) == typeof(string)) ? ((text as TResponse)) : (ToJsonModel<TResponse>(text));}public T? ToJsonModel<T>(string json){if (string.IsNullOrWhiteSpace(json)){return default(T);}JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions{PropertyNameCaseInsensitive = true};//   jsonSerializerOptions.Converters.Add(new DateTimeConverterUsingDateTimeParse());return JsonSerializer.Deserialize<T>(json, jsonSerializerOptions);}
}
 public interface IHttpService{/// <summary>/// Get访问WebAPI/// </summary>/// <param name="url">网页地址</param>/// <returns>访问失败返回错误原因,正确返回Json结果</returns>Task<TResponse?> GetAsync<TResponse>(string url) where TResponse : class;/// <summary>/// Post访问WebAPI/// </summary>/// <param name="url">网页地址</param>/// <returns>访问失败返回错误原因,正确返回Json结果</returns>Task<TResponse?> PostAsync<TResponse>(string url, object? Param) where TResponse : class;}

测试

using RestSharp;
using RestsharpDemo;
var service = new RestSharpService(new RestClient());
var url = "http://api.k780.com/?app=life.time&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
var r = await service.GetAsync<string>(url);
Console.WriteLine(r);
Console.ReadKey();

输出结果

RestSharp with polly 封装相关推荐

  1. WMS中RestSharp的使用

    RestSharp 简介 官方:RestSharp 可能是.NET 最流行的 HTTP 客户端库.它具有自动序列化和反序列化.请求和响应类型检测.多种身份验证和其他有用功能,正被数十万个项目使用. R ...

  2. 面向.NET开发人员的Dapr——服务调用

    目录: 面向.NET开发人员的Dapr--前言 面向.NET开发人员的Dapr--分布式世界 面向.NET开发人员的Dapr--俯瞰Dapr 面向.NET开发人员的Dapr--入门 面向.NET开发人 ...

  3. 拥抱.NET 5,从自研微服务框架开始

    " 2016年发布了.NET Core第一个正式版本,而.NET5也将在下个月就正式来临了,技术日新月异,也有点让人应接不暇.在框架设计上,.NET Framework的全家桶理念,培养了一 ...

  4. 开源的库RestSharp轻松消费Restful Service

    现在互联网上的服务接口都是Restful的,SOAP的Service已经不是主流..NET/Mono下如何消费Restful Service呢,再也没有了方便的Visual Studio的方便生产代理 ...

  5. 在 ASP.NET Core Web API中使用 Polly 构建弹性容错的微服务

    在 ASP.NET Core Web API中使用 Polly 构建弹性容错的微服务 https://procodeguide.com/programming/polly-in-aspnet-core ...

  6. .Net Core with 微服务 - Polly 服务降级熔断

    在我们实施微服务之后,服务间的调用变的异常频繁.多个服务之间可能是互相依赖的关系.某个服务出现故障或者是服务间的网络出现故障都会造成服务调用的失败,进而影响到某个业务服务处理失败.某一个服务调用失败轻 ...

  7. Flurl使用Polly实现重试Policy

    ❝ 在使用Flurl作为HttpClient向Server请求时,由于网络或者其它一些原因导致请求会有失败的情况,比如HttpStatusCode.NotFound.HttpStatusCode.Se ...

  8. .NetCore下使用Polly结合IHttpClientFactory实现聚合服务

    在使用微服务的过程中经常会遇到这样的情况,就目前我遇到的问题做下分析 情况一: 这里服务对于前后端分离情况来说,多使用查询服务,前端直接获取不同服务的数据展示,如果出现其中的服务失败,对业务数据无影响 ...

  9. Polly组件对微服务场景的价值

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

最新文章

  1. PyCairo 后端
  2. firefox 接受post 不完整_HTTP中GET与POST的区别,99 %的人都理解错了
  3. 读进程和写进程同步设计_浅谈unix进程进程间通信IPC原理
  4. Gallery with Video
  5. ruby打印_Ruby程序打印数字的力量
  6. dir612路由器虚拟服务器设置,dir612虚拟服务器设置
  7. java校验邮箱_Java正则表达式校验邮箱和手机号 | 学步园
  8. 标榜 AI 的百度又玩区块链,跟风布局“加密猫”?
  9. 数据库Sharding的基本思想和切分策略(转)
  10. 队列加分项:杨辉三角
  11. 设置session时间 php,php中设置session过期时间方法
  12. 安防蓝海带来亿万商机 汉王人脸通掀起产业风暴
  13. 网站优质内容细则及示例说明
  14. note:记各种资源
  15. 固态硬盘故障表现及数据恢复方案
  16. 《CSAPP》(第3版)答案(第三章)(一)
  17. HTML中nbsp 和空格的区别?
  18. ROSALIND答案——写在前面
  19. java一些必会算法(转自落尘曦的博客:http://blog.csdn.net/qq_23994787。 )
  20. 伯德图 matlab,Matlab/Simulink中bode图的画法

热门文章

  1. 遇黑链不惊慌4招轻松破
  2. 51单片机c语言按键扫描程序,单片机按键扫描数码管显示C语言程序
  3. python图片RGBA转RGB
  4. 你不得不知的几个互联网ID生成器方案
  5. imp-00403 oracle,12.2 以上版本的IMP-00403问题
  6. [附源码]计算机毕业设计JAVA基于JAVAWEB的高校实训管理系统
  7. CMake编译Nginx源码
  8. Linux使用rpm命令卸载软件
  9. ADDS:使用 PowerShell 创建 OU 结构
  10. FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled