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

相关推荐
roman_日积跬步-终至千里1 天前
【Docker多节点部署】基于“配置即身份“理念的 Docker 多节点 StarRocks 高可用集群自动化部署方案
java·docker·微服务
serendipity_hky1 天前
【微服务 - easy视频 | day03】服务与服务之间的调用
spring boot·spring cloud·微服务·架构
三口吃掉你1 天前
微服务之Nacos(注册中心、配置中心)
微服务·nacos·架构
聪明努力的积极向上2 天前
【C#】System.Text.Encoding.Default 属性在framework和.netcore中的区别
开发语言·c#·.netcore
陈果然DeepVersion2 天前
Java大厂面试真题:从Spring Boot到AI微服务的三轮技术拷问(一)
java·spring boot·redis·微服务·kafka·面试题·oauth2
zhangkaixuan4562 天前
Flink 写入 Paimon 流程:Checkpoint 与 Commit 深度剖析
java·开发语言·微服务·flink·paimon
论迹2 天前
【Spring Cloud微服务】-- DependencyManagement 和 Dependencies
spring·spring cloud·微服务
serendipity_hky2 天前
【微服务 - easy视频 | day01】准备工具+gateway网关及路由至内部服务
java·微服务·架构·gateway·springcloud
周杰伦_Jay3 天前
【Go微服务框架深度对比】Kratos、Go-Zero、Go-Micro、GoFrame、Sponge五大框架
开发语言·微服务·golang
回家路上绕了弯3 天前
海量日志分析:一天内最大在线人数与最长持续时间计算方案
后端·微服务