StackSpot.RestClient 1.0.0

dotnet add package StackSpot.RestClient --version 1.0.0                
NuGet\Install-Package StackSpot.RestClient -Version 1.0.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="StackSpot.RestClient" Version="1.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add StackSpot.RestClient --version 1.0.0                
#r "nuget: StackSpot.RestClient, 1.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install StackSpot.RestClient as a Cake Addin
#addin nuget:?package=StackSpot.RestClient&version=1.0.0

// Install StackSpot.RestClient as a Cake Tool
#tool nuget:?package=StackSpot.RestClient&version=1.0.0                

StackSpot Rest Client

Este componente foi projetado para apoiar os desenvolvedores a configurar a Instrumentação de circuit breaker, fallback e retry policy.

Versões suportadas

  • net5.0
  • net6.0

Features:

  • Retry com Estratégias Diferenciadas (Linear, Constant, Jitter (Exponencial))
  • Circuit Breaker
  • Circuit Breaker com Retry
  • Configuração via Service Collection
  • Propagação dos Headers Automáticos

Uso

1. Adicione o pacote NuGet StackSpot.RestClient ao seu projeto.
dotnet add package StackSpot.RestClient
2. Adicione ao seu IServiceCollection no Startup da aplicação ou Program.
        public void ConfigureServices(IServiceCollection services)
        {
            //Adicione a entrada para configurar os serviços basicos do REST COMPONENT
            services.ConfigureHttpClient();

            //Escolha a politica de retry conforme sua necessidade
            //as estrategias podem ser encontradas logo abaixo nesta documentação
            //Podemos utilizar a estrategia de retry default (Exponencial)
            services.AddHttpClientWithDefaultRetryPolicy<IGithubClient, GithubClient>();
        }

Implementação Service Client

Com a configuração realizada, vamos criar nosso primeiro client. O HttpClient será injetado com a politica de Retry configurada


public class GithubClient : IGithubClient
{
    public HttpClient Client { get; }

    public GithubClient(HttpClient client)
    {
        client.BaseAddress = new Uri("https://api.github.com/");
        client.DefaultRequestHeaders.Add("Accept","application/vnd.github.v3+json");
        client.DefaultRequestHeaders.Add("User-Agent","HttpClientFactory-Sample");
        this.Client = client;
    }

    public async Task<IEnumerable<GitHubIssue>> GetAspNetDocsIssues()
    {
        var response = await Client.GetAsync(
            "/repos/aspnet/AspNetCore.Docs/issues?state=open&sort=created&direction=desc");

        response.EnsureSuccessStatusCode();

        using var responseStream = await response.Content.ReadAsStreamAsync();
        
        return await JsonSerializer.DeserializeAsync<IEnumerable<GitHubIssue>>(responseStream);
    }
}

Escolhendo estratégia de Retry

Contamos com três estratégias de Retry, todas as estratégias contém um número de retry padrão (podendo ser alterado via service collection) de 5 (cinco) retentativas.

Exponencial ou Jitter

O Jitter é utilizado como estratégia default do Retry. O Jitter oferece retentativas com intervalos progressivos com uma formula matemática 2^x aonde x é a retentativa.

Caso o número de tentativa seja o valor padrão de 5 (cinco), teremos o seguinte exemplo:

Retentativas (Retries)

  1. 2 segundos a primeira retentativa
  2. 4 segundos a segunda retentativa
  3. 8 segundos a terceira retentativa
  4. 16 segundos a quarta retentativa
  5. 32 segundos a quinta retentativa
Configurando o Linear (Exponencial)
//Jitter é o default com o padrão de 5 retentativas
services.AddHttpClientWithDefaultRetryPolicy<IGithubClient, GithubClient>();

//Caso deseje alterar o valor
services.AddHttpClientWithRetryPolicy<IGithubClient, GithubClient>(new JitterStrategy(retryCount: 10));
Linear

O Linear oferece retentativas com intervalos linearmente baseado no default de intervalo de 500 milisegundos. Podemos alterar o número de tentativa e o seu intervalo padrão conforme nossa necessidade.

Exemplo de 5 Retentativas (Retries) com Default de 500 milisegundos

  1. 500 milisegundos a primeira retentativa
  2. 1000 milisegundos a segunda retentativa
  3. 1500 milisegundos a terceira retentativa
  4. 2000 milisegundos a quarta retentativa
  5. 2500 milisegundos a quinta retentativa
Configurando o Linear
//Adicionando o Linear com as configurações default (500 milisegundos de intervalor com 5 retries)
services.AddHttpClientWithRetryPolicy<IGithubClient, GithubClient>(new LinearStrategy());

//Alterando o Linear (1000 milisegundos de intervalos com 10 retries)
services.AddHttpClientWithRetryPolicy<IGithubClient, GithubClient>(
    new LinearStrategy(retryCount: 10, startStepInMilliSeconds: 1000));
Constant

O Constant oferece retentativas com intervalos constantes de 500 milisegundos. Podemos alterar o número de tentativa e o seu intervalo padrão conforme nossa necessidade.

Exemplo de 5 Retentativas (Retries) com Default de 500 milisegundos

  1. 500 milisegundos a primeira retentativa
  2. 500 milisegundos a segunda retentativa
  3. 500 milisegundos a terceira retentativa
  4. 500 milisegundos a quarta retentativa
  5. 500 milisegundos a quinta retentativa
Configurando o Linear
//Adicionando o Linear com as configurações default (500 milisegundos de intervalor com 5 retries)
services.AddHttpClientWithRetryPolicy<IGithubClient, GithubClient>(new ConstantStrategy());

//Alterando o Linear (1000 milisegundos de intervalos com 10 retries)
services.AddHttpClientWithRetryPolicy<IGithubClient, GithubClient>(
    new ConstantStrategy(retryCount: 10, startStepInMilliSeconds: 1000));

Utilizando estratégia de Retry com Circuit Break

Podemos utilizar o circuit break com qualquer estrategia
services.ConfigureHttpClient()
        .AddHttpClientWithDefaultCircuitBreakerPolicy<IGithubClient, GithubClient>();

//Fazendo a chamada
try 
{
    //Fará a rententativa com 5 vezes, caso não consiga abre o circuito com o valor padrão de 5 segundos
    var result = await gitHubclient.GetAspNetDocsIssues()
}
catch (BrokenCircuitException ex) 
{
    //Redireciona a ação
}
Utilizando com outras estratégias
services.ConfigureHttpClient()
        .AddHttpClientWithCircuitBreakerAndRetryPolicy<IGithubClient, GithubClient>(
            new CircuitBreakerDefaultConfiguration(retryCount: 10, breakDurationInSeconds: 15), 
            new LinearStrategy()
        );

//Fazendo a chamada
try 
{
    //Fará a rententativa com 10 vezes, caso não consiga abre o circuito com o valor padrão de 15 segundos
    var result = await gitHubclient.GetAspNetDocsIssues()
}
catch (BrokenCircuitException ex) 
{
    //Redireciona a ação
}
Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.0 307 1/28/2022