集成Nacos并新增Demo2微服务项目

本次提交实现了微服务架构扩展,新增 MicoService.Demo2 项目并集成 Nacos 配置中心与注册中心。主项目移除 WeatherForecast 相关代码,新增 TestController 支持服务间调用。完善配置文件,支持服务注册、发现与配置管理,为后续微服务通信和动态配置打下基础。
This commit is contained in:
YangQiang 2026-02-07 17:59:09 +08:00
parent 0c83a19d21
commit 945c4a8d05
12 changed files with 204 additions and 55 deletions

View File

@ -1,3 +1,4 @@
<Solution>
<Project Path="MicoService.Demo/MicoService.Demo.csproj" />
<Project Path="MicoService.Demo2/MicoService.Demo2.csproj" Id="efd7de63-eb5d-4687-8e58-967bc9d939e1" />
</Solution>

View File

@ -0,0 +1,56 @@
using Microsoft.AspNetCore.Mvc;
using Nacos.V2;
using System.Threading.Tasks;
namespace MicoService.Demo.Controllers
{
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
private readonly IConfiguration _configuration;
private readonly INacosNamingService _nacosNamingService;
public TestController(IConfiguration configuration,
INacosNamingService nacosNamingService)
{
this._configuration = configuration;
this._nacosNamingService = nacosNamingService;
}
/// <summary>
/// 演示:读取 Nacos 配置中心配置
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
[HttpGet("config/{key}")]
public string GetConfig(string key)
{
return _configuration[key];
}
/// <summary>
/// 演示:调用其他微服务
/// </summary>
[HttpGet("call")]
public async Task CallOtherService()
{
// 核心API获取单个实例内置负载均衡
var instance = await _nacosNamingService.SelectOneHealthyInstance("Mico_Demo2222");
if (instance == null)
{
Console.WriteLine("无可用实例");
}
// 拼接调用地址http://192.168.2.10:8080/api/xxx
var callUrl = $"http://{instance.Ip}:{instance.Port}/user/config/info";
}
}
}

View File

@ -1,38 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace MicoService.Demo.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries =
[
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
];
private readonly IConfiguration _configuration;
public WeatherForecastController(IConfiguration configuration)
{
this._configuration = configuration;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
[HttpGet("config/{key}")]
public string GetConfig(string key)
{
return _configuration[key];
}
}
}

View File

@ -10,13 +10,16 @@ namespace MicoService.Demo
{
var builder = WebApplication.CreateBuilder(args);
#region Nacos
// 配置 Nacos 配置中心
builder.Host.UseNacosConfig("nacos");
builder.Services.AddNacosV2Config(builder.Configuration);
// 配置 Nacos 注册发现
builder.Services.AddNacosAspNet(builder.Configuration);
builder.Services.AddNacosV2Naming(builder.Configuration);
builder.Services.AddNacosV2Naming(builder.Configuration);
#endregion
// Add services to the container.

View File

@ -1,13 +0,0 @@
namespace MicoService.Demo
{
public class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}

View File

@ -17,7 +17,7 @@
// Ncaos
"DefaultTimeOut": 15000,
"ListenInterval": 1000,
"ServiceName": "Mico_Demo1",
"ServiceName": "Mico_Demo1111",
"GroupName": "DEFAULT_GROUP",
"RegisterEnabled": true,
"InstanceEnabled": true,

View File

@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Mvc;
namespace MicoService.Demo2.Controllers
{
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
public UserController( IConfiguration configuration)
{
_configuration = configuration;
}
private readonly IConfiguration _configuration;
/// <summary>
/// 演示:读取 Nacos 配置中心配置
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
[HttpGet("config/{key}")]
public string GetConfig(string key)
{
return _configuration[key];
}
}
}

View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.2" />
<PackageReference Include="nacos-sdk-csharp.AspNetCore" Version="1.3.10" />
<PackageReference Include="nacos-sdk-csharp.Extensions.Configuration" Version="1.3.10" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,45 @@
using Nacos.AspNetCore.V2;
using Nacos.V2.DependencyInjection;
namespace MicoService.Demo2
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
#region Nacos
// 配置 Nacos 配置中心
builder.Host.UseNacosConfig("nacos");
builder.Services.AddNacosV2Config(builder.Configuration);
// 配置 Nacos 注册发现
builder.Services.AddNacosAspNet(builder.Configuration);
builder.Services.AddNacosV2Naming(builder.Configuration);
#endregion
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}

View File

@ -0,0 +1,14 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5181",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,29 @@
{
"nacos": {
// Nacos
"Namespace": "685d64ce-d088-400f-8cfe-a669a89015d0", // ID
"ServerAddresses": [ "http://192.168.2.9:8848" ], // Nacos/
"UserName": "nacos", // Nacos
"Password": "qwe123!@#", // Nacos
"Group": "DEFAULT_GROUP", //
"Listeners": [
{
"Optional": false,
"DataId": "demo2",
"Group": "DEFAULT_GROUP"
}
],
// Ncaos
"DefaultTimeOut": 15000,
"ListenInterval": 1000,
"ServiceName": "Mico_Demo2222",
"GroupName": "DEFAULT_GROUP",
"RegisterEnabled": true,
"InstanceEnabled": true,
"Ephemeral": true,
"ConfigUseRpc": true,
"NamingUseRpc": true,
"LBStrategy": "WeightRandom" //WeightRandom WeightRoundRobin
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}