public async Task <HealthCheckResult> CheckAsync(CancellationToken cancellationToken = default) { var timer = CheckTimer.Start(); try { var matchContent = _options.ExpectedContent != null; var completionOption = matchContent ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead; using (var response = await HttpClient .GetAsync(_uri, completionOption, cancellationToken) .ConfigureAwait(false)) { string contentString = null; // if we need to match the content, read it while still timing if (matchContent) { contentString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); } // all work has been finished, so stop the timer var timing = timer.Stop(); if (!response.IsSuccessStatusCode) { return(TimedHealthCheckResult.Unhealthy(timing, response.ReasonPhrase)); } if (timing > _options.UnhealthyThreshold) { return(TimedHealthCheckResult.Degraded(timing)); } if (!matchContent) { return(TimedHealthCheckResult.Healthy(timing)); } // need to match the response content if (_options.ExpectedContent.Equals(contentString)) { return(TimedHealthCheckResult.Healthy(timing)); } return(HealthCheckResult.Degraded("Response content does not match expected content")); } } catch (Exception ex) { return(TimedHealthCheckResult.Unhealthy(timer.Stop(), ex)); } }
public async Task <HealthCheckResult> CheckAsync(CancellationToken cancellationToken = default) { var timer = CheckTimer.Start(); try { var servers = GetServers().ToList(); var pingTasks = new List <Task <TimeSpan> >(); foreach (var s in servers) { if (!s.IsConnected) { continue; } pingTasks.Add(s.PingAsync()); } var connectedMsg = $"{pingTasks.Count}/{servers.Count} redis servers connected"; //Nothing connected if (pingTasks.Count == 0) { return(HealthCheckResult.Unhealthy(connectedMsg)); } //Get the average ping times var pingResults = await Task.WhenAll(pingTasks).ConfigureAwait(false); var avg = TimeSpan.FromTicks(Convert.ToInt64(pingResults.Average(p => p.Ticks))); //Some connected if (pingTasks.Count != servers.Count) { return(TimedHealthCheckResult.Degraded(avg, connectedMsg)); } //All connected //Check timing if (avg > _options.UnhealthyThreshold) { return(TimedHealthCheckResult.Degraded(avg)); } //All good return(TimedHealthCheckResult.Healthy(avg)); } catch (Exception ex) { return(TimedHealthCheckResult.Unhealthy(timer.Stop(), ex)); } }