LingAdmin/Backend/Services/ApiGateway/LingAdmin.ApiGateway/Controllers/HealthController.cs

94 lines
2.6 KiB
C#
Raw Permalink Normal View History

2026-04-16 18:13:06 +08:00
using Microsoft.AspNetCore.Mvc;
using LingAdmin.Shared.DTOs;
namespace LingAdmin.ApiGateway.Controllers;
/// <summary>
/// 健康检查控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class HealthController : ControllerBase
{
private readonly IConfiguration _configuration;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<HealthController> _logger;
public HealthController(
IConfiguration configuration,
IHttpClientFactory httpClientFactory,
ILogger<HealthController> logger)
{
_configuration = configuration;
_httpClientFactory = httpClientFactory;
_logger = logger;
}
/// <summary>
/// 网关健康检查
/// </summary>
[HttpGet]
public ActionResult<object> GetHealth()
{
return Ok(new
{
Status = "Healthy",
Service = "API Gateway",
Timestamp = DateTime.UtcNow,
Version = "1.0.0"
});
}
/// <summary>
/// 获取所有服务的健康状态
/// </summary>
[HttpGet("services")]
public async Task<ActionResult<object>> GetServicesHealth()
{
var services = new Dictionary<string, object>();
// Check Identity Service
services["identity-service"] = await CheckServiceHealthAsync(
_configuration["Services:IdentityService:BaseUrl"] ?? "http://localhost:5001");
// Check Authorization Service
services["authorization-service"] = await CheckServiceHealthAsync(
_configuration["Services:AuthorizationService:BaseUrl"] ?? "http://localhost:5002");
var allHealthy = services.Values.All(s => ((dynamic)s).Status == "Healthy");
return Ok(new
{
Status = allHealthy ? "Healthy" : "Degraded",
Timestamp = DateTime.UtcNow,
Services = services
});
}
private async Task<object> CheckServiceHealthAsync(string baseUrl)
{
try
{
var client = _httpClientFactory.CreateClient();
client.Timeout = TimeSpan.FromSeconds(5);
var response = await client.GetAsync($"{baseUrl}/api/health");
return new
{
Status = response.IsSuccessStatusCode ? "Healthy" : "Unhealthy",
StatusCode = (int)response.StatusCode
};
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Health check failed for {BaseUrl}", baseUrl);
return new
{
Status = "Unhealthy",
Error = ex.Message
};
}
}
}