.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"];
}
相关推荐
陈文锦丫3 小时前
微服务-----
java·数据库·微服务
櫻花3 小时前
微服务各大组件总结
微服务·云原生·架构
-大头.3 小时前
微服务架构深度演进与实践指南
微服务·云原生·架构
烛阴5 小时前
代码的“病历本”:深入解读C#常见异常
前端·c#
努力小周5 小时前
基于STM32的智能台灯系统设计与实现
stm32·单片机·嵌入式硬件·c#·毕业设计·毕设·javaee
van久5 小时前
.Net Core 学习:DbContextOptions<T> vs DbContextOptions 详细解析
java·学习·.netcore
arron88995 小时前
C# 项目源码进行全面的技术架构和调用逻辑分析。以下是系统性的技术方案
开发语言·架构·c#
拾忆,想起6 小时前
Dubbo序列化异常终结指南:从精准诊断到根治与防御
开发语言·前端·微服务·架构·php·dubbo·safari
一个帅气昵称啊6 小时前
.Net使用AgentFramework进行多Agent工作流编排-智能体AI开发
c#·.net·agentframework
czhc11400756637 小时前
Winform126 DataGrIdView ListView
c#·winform