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

相关推荐
bing.shao40 分钟前
微服务容错与监控体系设计
微服务·云原生·架构
天上掉下来个程小白3 小时前
Docker-14.项目部署-DockerCompose
运维·docker·微服务·容器
曾经的三心草18 小时前
微服务的编程测评系统11-jmeter-redis-竞赛列表
redis·jmeter·微服务
k↑1 天前
微服务之注册中心与ShardingSphere关于分库分表的那些事
数据库·微服务·架构·shardingsphere
Tadas-Gao1 天前
Java设计模式全景解析:从演进历程到创新实践
java·开发语言·微服务·设计模式·云原生·架构·系统架构
SirLancelot12 天前
K8s-kubernetes(二)资源限制-详细介绍
微服务·云原生·容器·kubernetes·k8s·devops·kubelet
为什么要内卷,摆烂不香吗2 天前
Docker容器技术全面解析(一):入门
docker·微服务·容器
孤狼程序员2 天前
【Spring Cloud 微服务】1.Hystrix断路器
java·spring boot·spring·微服务
为什么要内卷,摆烂不香吗2 天前
kubernetes(4) 微服务
linux·运维·微服务·容器·kubernetes
鼠鼠我捏,要死了捏4 天前
基于Spring Boot与gRPC的高性能微服务架构设计分享
spring boot·微服务·grpc