Asp .Net Core系列:使用 Nacos 实现配置管理和服务发现
官方示例:https://kgithub.com/nacos-group/nacos-sdk-csharp
安装 Nuget 包
dotnet add package nacos-sdk-csharp.AspNetCore
dotnet add package nacos-sdk-csharp.Extensions.Configuration
配置 appsettings.json
{
"Nacos": {
"ServerAddresses": ["http://127.0.0.1:8848/"],
//命名空间GUID,public默认没有
"Namespace": "",
"UserName": "nacos",
"Password": "nacos",
// 配置中心
"Listeners": [
{
"Group": "dev",
"DataId": "dotnet-nacos-service",
"Optional": false
}
],
// 服务发现
"ServiceName": "nacos-service",
"GroupName": ".NET Core",
// 权重
"Weight": 100,
"Metadata": {
"aa": "bb",
"cc": "dd"
}
}
}
添加服务和配置
using Nacos.AspNetCore.V2;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// 注册服务到Nacos
builder.Services.AddNacosAspNet(builder.Configuration, section: "Nacos");
// 添加配置中心
builder.Configuration.AddNacosV2Configuration(builder.Configuration.GetSection("Nacos"));
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseAuthorization();
app.MapControllers();
app.Run();
测试
using Microsoft.AspNetCore.Mvc;
namespace NacosDemo.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private IConfiguration _configuration;
public WeatherForecastController(IConfiguration configuration) => _configuration = configuration;
[HttpGet]
[Route("get")]
public string Get() => _configuration["RedisConn"];
}
}
服务发现
配置管理
postman
微信:17873041739