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

相关推荐
原野朝上18 小时前
如何使用Gradle搭建一个微服务项目
微服务·gradle
fanly111 天前
surging 发布命令行工具
微服务·surging
stark张宇9 天前
微服务架构必备:Gin + gRPC + Consul + Nacos + GORM 打造用户服务
微服务·gin·grpc
阿里云云原生12 天前
MSE Nacos Prompt 管理:让 AI Agent 的核心配置真正可治理
微服务·云原生
阿里云云原生12 天前
阿里云微服务引擎 MSE 及 API 网关 2026 年 1 月产品动态
微服务
麦聪聊数据13 天前
统一 Web SQL 平台如何收编企业内部的“野生数据看板”?
数据库·sql·低代码·微服务·架构
至此流年莫相忘13 天前
Kubernetes实战篇之服务发现
容器·kubernetes·服务发现
云司科技codebuddy13 天前
技术支持过硬Trae核心代理
大数据·运维·python·微服务
递归尽头是星辰13 天前
微服务事务分级治理:从 Seata 全模式到 TDSQL 实战
微服务·云原生·架构·分布式事务·事务分级治理
没有bug.的程序员13 天前
订单系统重构史诗:从单体巨兽到微服务矩阵的演进、数据一致性内核与分布式事务
java·微服务·矩阵·重构·分布式事务·数据一致性·订单系统