.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"];
}
相关推荐
月巴月巴白勺合鸟月半1 小时前
一个DevExpress的Docx文件处理的Bug的解决
c#·bug
陈果然DeepVersion1 小时前
Java大厂面试真题:Spring Boot+Kafka+AI智能客服场景全流程解析(四)
java·spring boot·微服务·kafka·面试题·rag·ai智能客服
.NET修仙日记2 小时前
第一章:从零开始构建你的第一个C#/.NET应用程序
c#·.net·.net core
123461615 小时前
互联网大厂Java面试:从Spring Boot到微服务的探索
java·数据库·spring boot·微服务·面试·mybatis·orm
陈果然DeepVersion5 小时前
Java大厂面试真题:Spring Boot+Kafka+AI智能客服场景全流程解析(一)
spring boot·微服务·kafka·消息队列·java面试·rag·ai智能客服
csdn_aspnet6 小时前
.NETCore、.NET 7 和 RabbitMQ 的发布-订阅模式
rabbitmq·.netcore·.net7.
爱吃香蕉的阿豪6 小时前
深入理解 .NET Core 中的 IServiceScopeFactory:用法、场景与静态类依赖注入
.netcore
m5655bj9 小时前
如何使用 Python 转换 Excel 工作表到 PDF 文档
开发语言·c#·excel
技术支持者python,php10 小时前
SUB设备电子狗加密狗开发
c#
唐青枫11 小时前
循环插入太慢?试试 C#.NET SqlBulkCopy,一次导入上百万数据
c#·.net