.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"];
}
相关推荐
无聊的老谢21 小时前
DDD 驱动的电信网络优化微服务建模实战
微服务·云原生·架构
魔法阵维护师21 小时前
从零开发游戏需要学习的c#模块,第三十五章(打包发布 —— 让别人玩你的游戏)
学习·游戏·c#
iCxhust1 天前
C# 程序,实现二进制文件十六进制查看器,支持按行定位
开发语言·单片机·嵌入式硬件·c#·微机原理·8086最小系统·8088单板机
Xin_ye100861 天前
C# 零基础到精通教程 - WPF 专题二:数据绑定与 MVVM
开发语言·c#·wpf
Xin_ye100861 天前
C# 零基础到精通教程 - WPF 专题一:WPF 入门与 XAML 基础
c#·wpf
兆。1 天前
LangChain文档处理集成指南:面向知识管理开发者
开发语言·langchain·c#
_oP_i1 天前
105、word 出现 {TOCO“1-2“HZ}
开发语言·c#·word
影寂ldy1 天前
C#构造函数 + 析构函数
开发语言·c#
_codemonster1 天前
30分钟快速搭建 Spring Cloud Alibaba 微服务实战(一)
微服务·架构·毕业设计·课程设计
Dongwoo Jeong2 天前
微服务架构(MSA)是如何诞生的?
微服务·云原生·架构