using MassTransit; using MassTransit.Message; using Microservice.Common; using Microservice.Common.Models; using Microservice.Common.Services; using Microsoft.AspNetCore.Mvc; using Nacos.V2; 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 IRequestClient _checkInvRequestClient; private readonly ILogger _logger; public TestController(IConfiguration configuration, INacosNamingService nacosNamingService, IServiceClient serviceClient, IUserService userService, IRequestClient checkInvRequestClient, ILogger logger) { this._configuration = configuration; this._nacosNamingService = nacosNamingService; this._serviceClient = serviceClient; this._userService = userService; this._checkInvRequestClient = checkInvRequestClient; 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("测试成功", "控制器正常工作")); } /// /// 演示 :通过MassTransit 使用 【请求-响应模式】 调用其他微服务的接口,检查库存是否充足 /// /// /// /// [HttpGet("check-inventory")] public async Task CheckInventoryAsync(string productId, int quantity) { try { var response = await _checkInvRequestClient.GetResponse(new CheckInventoryRequest(productId, quantity)); return response.Message.IsAvailable; } catch (RequestTimeoutException) { return false; } catch (Exception) { return false; } } /// /// 演示 :通过MassTransit 使用 【点对点模式】 调用其他微服务的接口,扣减库存 /// /// /// /// [HttpGet("dec-inventory")] public async Task DecInventoryAsync() { } } }