using Microsoft.AspNetCore.Mvc; using LingAdmin.Shared.DTOs; namespace LingAdmin.ApiGateway.Controllers; /// /// 健康检查控制器 /// [ApiController] [Route("api/[controller]")] public class HealthController : ControllerBase { private readonly IConfiguration _configuration; private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; public HealthController( IConfiguration configuration, IHttpClientFactory httpClientFactory, ILogger logger) { _configuration = configuration; _httpClientFactory = httpClientFactory; _logger = logger; } /// /// 网关健康检查 /// [HttpGet] public ActionResult GetHealth() { return Ok(new { Status = "Healthy", Service = "API Gateway", Timestamp = DateTime.UtcNow, Version = "1.0.0" }); } /// /// 获取所有服务的健康状态 /// [HttpGet("services")] public async Task> GetServicesHealth() { var services = new Dictionary(); // 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 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 }; } } }