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

相关推荐
步、步、为营9 分钟前
.net微服务框架dapr保存和获取状态
微服务·架构·.net
guojl3 小时前
微服务OpenFeign源码分析
spring cloud·微服务
guojl3 小时前
微服务OpenFeign使用手册
spring cloud·微服务
Code季风1 天前
Gin Web 层集成 Viper 配置文件和 Zap 日志文件指南(下)
前端·微服务·架构·go·gin
Code季风1 天前
Gin Web 服务集成 Consul:从服务注册到服务发现实践指南(下)
java·前端·微服务·架构·go·gin·consul
掘金-我是哪吒2 天前
分布式微服务系统架构第156集:JavaPlus技术文档平台日更-Java线程池使用指南
java·分布式·微服务·云原生·架构
DavidSoCool2 天前
RabbitMQ使用topic Exchange实现微服务分组订阅
分布式·微服务·rabbitmq
掘金-我是哪吒2 天前
分布式微服务系统架构第158集:JavaPlus技术文档平台日更-JVM基础知识
jvm·分布式·微服务·架构·系统架构
Kookoos2 天前
ABP VNext + Tye:本地微服务编排与调试
微服务·云原生·架构·tye
guojl2 天前
Ribbon原理和源码分析
spring cloud·微服务