.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"];
}
相关推荐
pnoker3 小时前
拆解 IoT DC3:六层微服务架构
java·物联网·spring cloud·微服务·架构
呆呆敲代码的小Y4 小时前
【游戏开发】Lua 与 C# 交互原理解析
c#·lua·交互·热更新·lua与c#交互·游戏热更新
「、皓子~5 小时前
海狸IM 2.1 正式发布
flutter·微服务·golang·electron·开源软件·im·海狸im
用户298698530145 小时前
PDF 转纯文本(TXT)免费攻略:轻松提取文字内容
人工智能·后端·c#
呆呆敲代码的小Y5 小时前
【游戏开发】C# 中的迭代器
java·开发语言·c#·迭代器
星期一研究室6 小时前
原来每天在听的网易云是这样的……
微服务·产品·设计
2601_9622184715 小时前
万象生鲜系统区块链溯源技术帮助生鲜企业搭建食品安全数字化体系
大数据·运维·微服务·云原生·架构
2601_962065251 天前
【图文详解】什么是微服务?什么是SpringCloud?
spring cloud·微服务·架构
格林威1 天前
C# 相机Burst模式图像采集:使用相机内存配合OpenCvSharp和Halcon实现短时间的高速采集的方法
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机