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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?