.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"];
}
相关推荐
淡海水13 小时前
02-02-原理篇-分代GC
算法·unity·c#·游戏引擎·.net·gc
BD_Marathon14 小时前
多轮对话聊天机器人
开发语言·机器人·c#
czhc114007566314 小时前
设备标定页防呆为何失效:草稿与真值的错位
c#
周杰伦fans17 小时前
轻量模型高并发推理优化技巧
开发语言·人工智能·c#
周杰伦fans17 小时前
C#对话摘要降低Token消耗
人工智能·后端·c#
贾斯汀frank21 小时前
Spring Boot + K8s + Istio 与 Spring Cloud:微服务治理能力对比
spring cloud·微服务·istio
en.en..21 小时前
分清 b 与 B:比特、字节(告别8倍、容量、缓冲区误区)
c#
ly768921 小时前
ISR 收缩与 HW 推进:副本同步的边界条件与 UnderReplicated 排障
数据库·kafka·c#·linq·isr·hw·副本同步
miofly21 小时前
GitHub 今日推荐|REDox:64 位 token 表示结构化数据,内存占用降 70% 支持多格式互转
开源·c#·github
自强的小白21 小时前
微服务之间的依赖传递和调用(实体类的模块传递以及负载均衡的调用!)注册中心
java·微服务