.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"];
}
相关推荐
samble14 小时前
从零搭建灌装监控系统(十七):LiveCharts 实时温度曲线
c#·wpf·mvvm·modbus·工业控制
wewowilling17 小时前
认识微服务
java·运维·微服务·springcloud
众链网络20 小时前
Agent 的成本大头不在“写“,在“判断“:拆解专用决策模型的三层架构
java·开发语言·人工智能·微服务
我不是阵雨1 天前
分布式事务难题与实战解法全解析
分布式·微服务·架构
淡海水1 天前
02-07-原理篇-GC暂停时间的本质
开发语言·unity·c#·gc·暂停时间
做运维的阿瑞1 天前
公有云算力布局的技术逻辑与工程实践
微服务·云计算·csdn开发云
m0_646429971 天前
从零搭建 Spring Boot + Nacos + MySQL + OpenFeign + Docker Compose 微服务项目
微服务
小羊没烦恼!1 天前
OS X 上使用.NET开发应用程序
开发语言·前端·数据库·人工智能·c#·策略模式
Behavior1 天前
Unity 7.0 Alpha 拆解:编辑器干掉 Mono 换 CoreCLR
c#·unity3d·游戏开发
淡海水1 天前
02-06-原理篇-增量式GC与并发GC
算法·unity·c#·并发·gc·增量