95 lines
3.2 KiB
C#
95 lines
3.2 KiB
C#
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<TestController> _logger;
|
|
|
|
public TestController(IConfiguration configuration,
|
|
INacosNamingService nacosNamingService,
|
|
IServiceClient serviceClient,
|
|
IUserService userService,
|
|
ILogger<TestController> logger)
|
|
{
|
|
this._configuration = configuration;
|
|
this._nacosNamingService = nacosNamingService;
|
|
this._serviceClient = serviceClient;
|
|
this._userService = userService;
|
|
this._logger = logger;
|
|
}
|
|
|
|
|
|
|
|
/// <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.Demo", "This is a test config info");
|
|
return Ok(ApiResponseHelper.Success(data, "获取配置信息成功"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// 演示:使用微服务通讯客户端调用其他微服务
|
|
/// </summary>
|
|
[HttpGet("call")]
|
|
public async Task<IActionResult> CallOtherService()
|
|
{
|
|
try
|
|
{
|
|
// 使用用户服务调用用户微服务
|
|
var result = await this._userService.GetUserInfoAsync();
|
|
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));
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 演示:测试控制器是否正常工作
|
|
/// </summary>
|
|
[HttpGet("test")]
|
|
public IActionResult Test()
|
|
{
|
|
return Ok(ApiResponseHelper.Success("测试成功", "控制器正常工作"));
|
|
}
|
|
|
|
|
|
}
|
|
}
|