.net core接入nacos注册服务并使用配置中心

1、安装依赖

Nuget包:nacos-sdk-csharp.Extensions.Configuration和nacos-sdk-csharp.AspNetCore

2、在appsettings.json中配置

复制代码
"nacos": {
    "ServerAddresses": [
      "http://localhost:8848/"
    ],
    "DefaultTimeOut": 15000,
    "Namespace": "xxxxx",//命名空间
    "ListenInterval": 5000,
    "ServiceName": "testService",//服务名称
    "GroupName": "DEFAULT_GROUP",//组明
    "ClusterName": "DEFAULT",
    "Ip": "",
    "PreferredNetworks": "",
    "Port": 0,
    "Weight": 1,
    "RegisterEnabled": true,
    "InstanceEnabled": true,
    "Ephemeral": true,
    "Secure": false,
    "AccessKey": "",
    "SecretKey": "",
    "UserName": "nacos",//用户名
    "Password": "nacos",//密码
    "ConfigUseRpc": false,
    "NamingUseRpc": false,
    "NamingLoadCacheAtStart": "",
    "LBStrategy": "WeightRandom",
    //下方是注册中心专用,如果不需要配置中心则可不配置
    "Listeners": [
      {
        "Group": "DEFAULT_GROUP",
        "DataId": "test-dev.json",
        "Optional": false
      }
    ]
  }

3、在Program.cs中注入服务

复制代码
builder.Services.AddNacosAspNet(builder.Configuration, section:"nacos");
builder.Configuration.AddNacosV2Configuration(builder.Configuration.GetSection("nacos"));//如果不使用服务注册中心可不写他

4、注.net 中需要添加如下开放IP

复制代码
builder.WebHost.UseUrls("http://*:5065");

5、启动可看到

6、如果配置了nacos的配置文件的话

测试用例

复制代码
public class TestController : ControllerBase
{
  private readonly IConfiguration _configuration;

    public TestController(IConfiguration configuration)
    {
        this._configuration = configuration;
    }
    
    [HttpGet("getConfig")]
    public string getConfig() => _configuration["a1"];
}
相关推荐
山檐雾6 小时前
OctreeNode
unity·c#·八叉树
better_liang8 小时前
每日Java面试场景题知识点之-Redisson热门使用场景
java·redis·微服务·分布式锁·redisson·分布式系统
QfC92C02p9 小时前
C# 中的 Span 和内存:.NET 中的高性能内存处理
java·c#·.net
Yuri X-202110 小时前
VS2022实战测试题——2
程序人生·c#·个人开发·visual studio
公子小六10 小时前
基于.NET的Windows窗体编程之WinForms布局简介
windows·microsoft·c#·.net
zaim111 小时前
计算机的错误计算(二百二十六)
java·python·c#·c·错数·mpmath
却话巴山夜雨时i11 小时前
Java大厂面试:从Spring Boot到微服务的深度剖析
java·spring boot·spring cloud·微服务·分布式事务·大厂面试
zs宝来了11 小时前
Dubbo SPI 机制:ExtensionLoader 原理深度解析
微服务·dubbo·spi·源码解析·extensionloader
William_cl11 小时前
[特殊字符]C# ASP.NET 架构封神之路:分层 + 仓储 + EFCore,写出企业级可维护代码!
架构·c#·asp.net
tq6J5Yg1411 小时前
.NET 10 & C# 14 New Features 新增功能介绍-带修饰符的简单 lambda 参数
开发语言·c#·.net