using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Nacos.V2; using System.Threading.Tasks; using Microservice.Common; using Microservice.Common.Models; using Microservice.Common.Services; namespace MicoService.Demo.Controllers { [ApiController] [Route("[controller]")] public class TestController : ControllerBase { private readonly IConfiguration _configuration; private readonly INacosNamingService _nacosNamingService; private readonly IServiceClient _serviceClient; private readonly IUserService _userService; private readonly ILogger _logger; public TestController(IConfiguration configuration, INacosNamingService nacosNamingService, IServiceClient serviceClient, IUserService userService, ILogger logger) { this._configuration = configuration; this._nacosNamingService = nacosNamingService; this._serviceClient = serviceClient; this._userService = userService; this._logger = logger; } /// /// 演示:读取 Nacos 配置中心配置 /// /// /// [HttpGet("config/{key}")] public IActionResult GetConfig(string key) { var value = _configuration[key]; return Ok(ApiResponseHelper.Success(value, "获取配置成功")); } /// /// 演示:提供给其他服务调用的接口 /// [HttpGet("config/info")] public IActionResult GetConfigInfo() { var data = new ConfigInfoModel("Hello from MicoService.Demo", "This is a test config info"); return Ok(ApiResponseHelper.Success(data, "获取配置信息成功")); } /// /// 演示:使用微服务通讯客户端调用其他微服务 /// [HttpGet("call")] public async Task CallOtherService() { try { // 使用用户服务调用用户微服务 var result = await this._userService.GetUserInfoAsync(); var data = new ServiceCallResultModel("调用成功", result); return Ok(ApiResponseHelper.Success(data, "服务调用成功")); } catch (ApiException ex) { return StatusCode(ex.StatusCode, ApiResponseHelper.Error(System.Net.HttpStatusCode.InternalServerError, ex.Message)); } catch (Exception ex) { return StatusCode(500, ApiResponseHelper.Error(System.Net.HttpStatusCode.InternalServerError, "调用失败: " + ex.Message)); } } /// /// 演示:测试控制器是否正常工作 /// [HttpGet("test")] public IActionResult Test() { return Ok(ApiResponseHelper.Success("测试成功", "控制器正常工作")); } } }