ExampleHealthCheck.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using Microsoft.Extensions.Diagnostics.HealthChecks;
  2. namespace OASystem.API.HealthChecks
  3. {
  4. public class ExampleHealthCheck : IHealthCheck
  5. {
  6. public Task<HealthCheckResult> CheckHealthAsync(
  7. HealthCheckContext context,
  8. CancellationToken cancellationToken = default)
  9. {
  10. // Here you would check the health of your dependencies
  11. // For example, check database connection, external services, etc.
  12. var isHealthy = true; // Replace with actual health check logic
  13. if (isHealthy)
  14. {
  15. return Task.FromResult(
  16. HealthCheckResult.Healthy("A healthy result."));
  17. }
  18. return Task.FromResult(
  19. new HealthCheckResult(
  20. context.Registration.FailureStatus, "An unhealthy result."));
  21. }
  22. }
  23. public class DatabaseHealthCheck : IHealthCheck
  24. {
  25. public async Task<HealthCheckResult> CheckHealthAsync(
  26. HealthCheckContext context,
  27. CancellationToken cancellationToken = default)
  28. {
  29. try
  30. {
  31. // 模拟数据库检查
  32. await Task.Delay(100, cancellationToken);
  33. return HealthCheckResult.Healthy("Database is OK");
  34. }
  35. catch (Exception ex)
  36. {
  37. return HealthCheckResult.Unhealthy("Database failure", ex);
  38. }
  39. }
  40. }
  41. public class ApiHealthCheck : IHealthCheck
  42. {
  43. private readonly HttpClient _httpClient;
  44. public ApiHealthCheck(HttpClient httpClient) => _httpClient = httpClient;
  45. public async Task<HealthCheckResult> CheckHealthAsync(
  46. HealthCheckContext context,
  47. CancellationToken cancellationToken = default)
  48. {
  49. var response = await _httpClient.GetAsync("ping", cancellationToken);
  50. return response.IsSuccessStatusCode
  51. ? HealthCheckResult.Healthy("API is responsive")
  52. : HealthCheckResult.Degraded($"API response: {response.StatusCode}");
  53. }
  54. }
  55. }