Mico.Demo/MicoService.Demo2/Controllers/UserController.cs

67 lines
2.3 KiB
C#
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.AspNetCore.Mvc;
using Microservice.Common;
using Microservice.Common.Models;
namespace MicoService.Demo2.Controllers
{
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
public UserController( IConfiguration configuration, IServiceClient serviceClient)
{
_configuration = configuration;
_serviceClient = serviceClient;
}
private readonly IConfiguration _configuration;
private readonly IServiceClient _serviceClient;
/// <summary>
/// 演示:读取 Nacos 配置中心配置
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
[HttpGet("config/{key}")]
public IActionResult GetConfig(string key)
{
var value = _configuration[key];
return Ok(ApiResponseHelper.Success(value, "获取配置成功"));
}
/// <summary>
/// 演示:提供给其他服务调用的接口
/// </summary>
[HttpGet("config/info")]
public IActionResult GetConfigInfo()
{
var data = new ConfigInfoModel("Hello from MicoService.Demo2", "This is a test config info");
return Ok(ApiResponseHelper.Success(data, "获取配置信息成功"));
}
/// <summary>
/// 演示:调用其他微服务
/// </summary>
[HttpGet("call-other")]
public async Task<IActionResult> CallOtherService()
{
try
{
// 使用微服务通讯客户端调用 Mico_Demo1111 服务
var result = await _serviceClient.GetAsync<ConfigInfoModel>("Mico_Demo1111", "/test/config/info");
var data = new ServiceCallResultModel<ConfigInfoModel>("调用成功", 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));
}
}
}
}