.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"];
}
相关推荐
心念枕惊17 小时前
.NET CORE 授权进阶-角色、策略与动态权限实现
java·前端·.netcore
beibeix201518 小时前
MITK中微服务三套注册表数据结构分析
微服务·mitk
geovindu19 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
Wang's Blog19 小时前
Go-Zero项目开发34: 微服务超时控制与重试机制实践
开发语言·微服务·golang·go-zero
X-⃢_⃢-X21 小时前
四、OpenFeign远程调用
java·微服务·springboot·springcloud
小羊先生car1 天前
RTOS-F429-HAL-(动/静态)任务的创建(2026/7/27)
开发语言·算法·c#
beibeix20151 天前
MITK中两种微服务的三层架构实现对比
微服务·mitk
地球驾驶员1 天前
NX二次开发C#-获取体的外表面
开发语言·c#
在水一缸1 天前
深入浅出:Node.js 下一代 ORM 架构设计与实战解析
数据库·微服务·云原生·node.js·orm·架构设计
Wang's Blog1 天前
Go-Zero项目开发30: 微服务配置中心的设计与实现
开发语言·微服务·golang·go-zero