Skip to content

Basic example

Alex edited this page Jan 29, 2021 · 1 revision

Lets take a basic example.

Lets say we run a "IsItUp" service. The idea is that people call you to check whether some website or service is up or down. We also only want to check the site a max of once per second, if multiple people are looking to check at the same time.

// The IsUpResult class.
class IsUpResult
{
    private readonly string site;
    private readonly bool isUp;

    public IsUpResult(string site, bool isUp)
    {
        this.site = site;
        this.isUp = isUp;
    }

    public string Site => this.site;

    public bool IsUp => this.isUp;

    public override int GetHashCode()
    {
        return this.site.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        return base.Equals(obj as IsUpResult);
    }

    public bool Equals(IsUpResult other)
    {
        return this.site == other.Site && this.isUp == other.IsUp;
    }

}

A really simple class for holding the value of the response.

And our command implementation

class IsItUpCommand : ResilientCommand<IsUpResult>
{
    private readonly string site;
    private readonly HttpClient client;

    public IsItUpCommand(string site) : base(
        configuration: CommandConfiguration.CreateConfiguration(config => 
            // Enabled collapsing, for a window of 1 second. rest of configuration will be standard.
            config.CollapserSettings = new CollapserSettings(isEnabled: true, window: TimeSpan.FromSeconds(1))
        ))
    {
        this.site = site;
        this.client = new HttpClient();
    }

    protected override async Task<IsUpResult> RunAsync(CancellationToken cancellationToken)
    {
        var response = await client.GetAsync(this.site);
        response.EnsureSuccessStatusCode(); // Throws if non-success.

        return new IsUpResult(this.site, true);
    }

    protected override IsUpResult Fallback()
    {
        return new IsUpResult(this.site, false);
    }
}
Clone this wiki locally