12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- using Microsoft.Extensions.Diagnostics.HealthChecks;
- namespace OASystem.API.HealthChecks
- {
- public class ExampleHealthCheck : IHealthCheck
- {
- public Task<HealthCheckResult> CheckHealthAsync(
- HealthCheckContext context,
- CancellationToken cancellationToken = default)
- {
- // Here you would check the health of your dependencies
- // For example, check database connection, external services, etc.
- var isHealthy = true; // Replace with actual health check logic
- if (isHealthy)
- {
- return Task.FromResult(
- HealthCheckResult.Healthy("A healthy result."));
- }
- return Task.FromResult(
- new HealthCheckResult(
- context.Registration.FailureStatus, "An unhealthy result."));
- }
- }
- public class DatabaseHealthCheck : IHealthCheck
- {
- public async Task<HealthCheckResult> CheckHealthAsync(
- HealthCheckContext context,
- CancellationToken cancellationToken = default)
- {
- try
- {
- // 模拟数据库检查
- await Task.Delay(100, cancellationToken);
- return HealthCheckResult.Healthy("Database is OK");
- }
- catch (Exception ex)
- {
- return HealthCheckResult.Unhealthy("Database failure", ex);
- }
- }
- }
- public class ApiHealthCheck : IHealthCheck
- {
- private readonly HttpClient _httpClient;
- public ApiHealthCheck(HttpClient httpClient) => _httpClient = httpClient;
- public async Task<HealthCheckResult> CheckHealthAsync(
- HealthCheckContext context,
- CancellationToken cancellationToken = default)
- {
- var response = await _httpClient.GetAsync("ping", cancellationToken);
- return response.IsSuccessStatusCode
- ? HealthCheckResult.Healthy("API is responsive")
- : HealthCheckResult.Degraded($"API response: {response.StatusCode}");
- }
- }
- }
|