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

相关推荐
小江的记录本1 天前
【Spring全家桶】Spring Cloud 2023.0.x:微服务核心理论、CAP/BASE定理(附《思维导图》+《面试高频考点清单》)
java·spring boot·后端·spring·spring cloud·微服务·面试
Demon1_Coder1 天前
Day4-微服务-Seata默认事务
java·数据库·微服务
huipeng9261 天前
企业级微服务开发实战(二):微服务基础设施搭建与中间件部署
java·redis·mysql·spring cloud·微服务·nacos·rabbitmq
Jabes.yang1 天前
Java电商订单系统面试全流程解析:接口设计、数据库、微服务与分布式事务实战
java·微服务·mybatis·分布式事务·电商·订单系统·接口设计
Jabes.yang1 天前
Java面试实录:AIGC场景下的Stream、微服务、Redis、Kafka与安全实战
java·spring boot·redis·微服务·面试·kafka·aigc
努力搬砖的咸鱼1 天前
容器编排底层原理:Kubernetes 网络模型与 CNI 插件
网络·微服务·云原生·容器·架构·kubernetes
kakawzw2 天前
微服务组件源码2——Spring Ribbon原理(基于RibbonLoadBalancerClient)
java·微服务·ribbon
Demon1_Coder2 天前
Day3-微服务-Sentinel-具体使用
java·微服务·sentinel
qingy_20462 天前
【架构师之路】绪论
微服务·云原生·架构
追寻少年2 天前
Kubernetes 服务发现和域名解析-cnblog
容器·kubernetes·服务发现