diff --git a/MicoService.Demo.slnx b/MicoService.Demo.slnx
index e84a1f1..33f9471 100644
--- a/MicoService.Demo.slnx
+++ b/MicoService.Demo.slnx
@@ -1,4 +1,6 @@
+
+
diff --git a/MicoService.Demo/Controllers/TestController.cs b/MicoService.Demo/Controllers/TestController.cs
index 66bfc08..a7c15d8 100644
--- a/MicoService.Demo/Controllers/TestController.cs
+++ b/MicoService.Demo/Controllers/TestController.cs
@@ -1,6 +1,10 @@
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;
namespace MicoService.Demo.Controllers
{
@@ -11,44 +15,74 @@ namespace MicoService.Demo.Controllers
private readonly IConfiguration _configuration;
private readonly INacosNamingService _nacosNamingService;
+ private readonly IServiceClient _serviceClient;
+ private readonly ILogger _logger;
public TestController(IConfiguration configuration,
- INacosNamingService nacosNamingService)
+ INacosNamingService nacosNamingService,
+ IServiceClient serviceClient,
+ ILogger logger)
{
this._configuration = configuration;
this._nacosNamingService = nacosNamingService;
+ this._serviceClient = serviceClient;
+ this._logger = logger;
}
///
- /// ʾȡ Nacos
+ /// 演示:读取 Nacos 配置中心配置
///
///
///
[HttpGet("config/{key}")]
- public string GetConfig(string key)
+ public IActionResult GetConfig(string key)
{
- return _configuration[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()
+ public async Task CallOtherService()
{
- // APIȡʵøؾ⣩
- var instance = await _nacosNamingService.SelectOneHealthyInstance("Mico_Demo2222");
-
- if (instance == null)
+ try
{
- Console.WriteLine("ʵ");
+ // 使用微服务通讯客户端调用 Mico_Demo2222 服务
+ var result = await this._serviceClient.GetAsync("Mico_Demo2222", "/User/config/info");
+ 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));
+ }
+ }
- // ƴӵõַ磺http://192.168.2.10:8080/api/xxx
- var callUrl = $"http://{instance.Ip}:{instance.Port}/user/config/info";
-
+ ///
+ /// 演示:测试控制器是否正常工作
+ ///
+ [HttpGet("test")]
+ public IActionResult Test()
+ {
+ return Ok(ApiResponseHelper.Success("测试成功", "控制器正常工作"));
}
diff --git a/MicoService.Demo/MicoService.Demo.csproj b/MicoService.Demo/MicoService.Demo.csproj
index 25d4627..58aee2c 100644
--- a/MicoService.Demo/MicoService.Demo.csproj
+++ b/MicoService.Demo/MicoService.Demo.csproj
@@ -10,6 +10,11 @@
+
+
+
+
+
diff --git a/MicoService.Demo/Program.cs b/MicoService.Demo/Program.cs
index e639217..47c62e3 100644
--- a/MicoService.Demo/Program.cs
+++ b/MicoService.Demo/Program.cs
@@ -1,6 +1,7 @@
using Nacos.AspNetCore.V2;
using Nacos.V2.DependencyInjection;
+using Microservice.Common;
namespace MicoService.Demo
{
@@ -27,6 +28,9 @@ namespace MicoService.Demo
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
+
+ // 注册微服务通讯客户端
+ builder.Services.AddServiceClient();
var app = builder.Build();
diff --git a/MicoService.Demo/appsettings.json b/MicoService.Demo/appsettings.json
index 10f68b8..81d2855 100644
--- a/MicoService.Demo/appsettings.json
+++ b/MicoService.Demo/appsettings.json
@@ -1,8 +1,8 @@
{
"Logging": {
"LogLevel": {
- "Default": "Information",
- "Microsoft.AspNetCore": "Warning"
+ "Default": "Debug",
+ "Microsoft.AspNetCore": "Debug"
}
},
"AllowedHosts": "*"
diff --git a/MicoService.Demo2/Controllers/UserController.cs b/MicoService.Demo2/Controllers/UserController.cs
index 9778b80..18e431f 100644
--- a/MicoService.Demo2/Controllers/UserController.cs
+++ b/MicoService.Demo2/Controllers/UserController.cs
@@ -1,4 +1,6 @@
-using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc;
+using Microservice.Common;
+using Microservice.Common.Models;
namespace MicoService.Demo2.Controllers
{
@@ -7,20 +9,56 @@ namespace MicoService.Demo2.Controllers
public class UserController : ControllerBase
{
- public UserController( IConfiguration configuration)
+ public UserController( IConfiguration configuration, IServiceClient serviceClient)
{
_configuration = configuration;
+ _serviceClient = serviceClient;
}
private readonly IConfiguration _configuration;
+ private readonly IServiceClient _serviceClient;
///
/// 演示:读取 Nacos 配置中心配置
///
///
///
[HttpGet("config/{key}")]
- public string GetConfig(string key)
+ public IActionResult GetConfig(string key)
{
- return _configuration[key];
+ var value = _configuration[key];
+ return Ok(ApiResponseHelper.Success(value, "获取配置成功"));
+ }
+
+ ///
+ /// 演示:提供给其他服务调用的接口
+ ///
+ [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, "获取配置信息成功"));
+ }
+
+ ///
+ /// 演示:调用其他微服务
+ ///
+ [HttpGet("call-other")]
+ public async Task CallOtherService()
+ {
+ try
+ {
+ // 使用微服务通讯客户端调用 Mico_Demo1111 服务
+ var result = await _serviceClient.GetAsync("Mico_Demo1111", "/test/config/info");
+ 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));
+ }
}
diff --git a/MicoService.Demo2/MicoService.Demo2.csproj b/MicoService.Demo2/MicoService.Demo2.csproj
index 25d4627..58aee2c 100644
--- a/MicoService.Demo2/MicoService.Demo2.csproj
+++ b/MicoService.Demo2/MicoService.Demo2.csproj
@@ -10,6 +10,11 @@
+
+
+
+
+
diff --git a/MicoService.Demo2/Program.cs b/MicoService.Demo2/Program.cs
index ffc9230..d4e835c 100644
--- a/MicoService.Demo2/Program.cs
+++ b/MicoService.Demo2/Program.cs
@@ -1,6 +1,7 @@
using Nacos.AspNetCore.V2;
using Nacos.V2.DependencyInjection;
+using Microservice.Common;
namespace MicoService.Demo2
{
@@ -25,6 +26,9 @@ namespace MicoService.Demo2
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
+
+ // 注册微服务通讯客户端
+ builder.Services.AddServiceClient();
var app = builder.Build();
diff --git a/Microservice.Common.Tests/Microservice.Common.Tests.csproj b/Microservice.Common.Tests/Microservice.Common.Tests.csproj
new file mode 100644
index 0000000..939afb9
--- /dev/null
+++ b/Microservice.Common.Tests/Microservice.Common.Tests.csproj
@@ -0,0 +1,28 @@
+
+
+
+ net10.0
+ enable
+ enable
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Microservice.Common.Tests/ServiceClientTests.cs b/Microservice.Common.Tests/ServiceClientTests.cs
new file mode 100644
index 0000000..58f5b09
--- /dev/null
+++ b/Microservice.Common.Tests/ServiceClientTests.cs
@@ -0,0 +1,256 @@
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.Extensions.Logging;
+using Moq;
+using Nacos.V2;
+using Nacos.V2.Common;
+using Nacos.V2.Naming.Dtos;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Threading.Tasks;
+using Xunit;
+
+namespace Microservice.Common.Tests
+{
+ public class ServiceClientTests
+ {
+ private readonly Mock _nacosNamingServiceMock;
+ private readonly HttpClient _httpClient;
+ private readonly Mock> _loggerMock;
+ private readonly ServiceClient _serviceClient;
+
+ public ServiceClientTests()
+ {
+ // 初始化模拟对象
+ _nacosNamingServiceMock = new Mock();
+ _loggerMock = new Mock>();
+
+ // 创建一个测试用的 HttpClient
+ var httpClientHandler = new HttpClientHandler
+ {
+ ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
+ };
+ _httpClient = new HttpClient(httpClientHandler);
+
+ // 创建 ServiceClient 实例
+ _serviceClient = new ServiceClient(_nacosNamingServiceMock.Object, _loggerMock.Object);
+ }
+
+ [Fact]
+ public async Task GetAsync_ShouldReturnSuccess_WhenServiceIsAvailable()
+ {
+ // Arrange
+ var serviceName = "TestService";
+ var endpoint = "/api/test";
+ var expectedResponse = new { Message = "Test Response" };
+
+ // 模拟 Nacos 服务发现返回一个健康的实例
+ var instance = new Instance
+ {
+ Ip = "127.0.0.1",
+ Port = 8080,
+ Healthy = true,
+ Enabled = true
+ };
+ _nacosNamingServiceMock.Setup(x => x.SelectOneHealthyInstance(serviceName)).ReturnsAsync(instance);
+
+ // 创建一个测试服务器
+ var testServer = new TestServer(new WebApplicationFactory