.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"];
}
相关推荐
颜x小13 分钟前
[C#]泛型类与泛型方法
开发语言·c++·c#
caishenzhibiao23 分钟前
顺势交易矩阵主图 同花顺期货通指标
java·c语言·c#
一知半解仙1 小时前
从0到1!Spring Cloud微服务无缝集成AI智能体:架构设计+核心源码+生产落地全指南
人工智能·spring cloud·微服务
TDengine (老段)1 小时前
TDengine Node.js 与 C# 连接器 — Web 服务与 .NET 集成
大数据·数据库·node.js·c#·.net·时序数据库·tdengine
豆瓣鸡1 小时前
微服务项目生产环境全链路架构:从前端访问到网关鉴权、服务调用、中间件与网络安全
微服务·架构
河西石头2 小时前
再谈C#的抽象类和接口:从“适配器”到“毛坯房”的设计哲学
开发语言·c#·接口·依赖注入·抽象类·依赖倒挂
颜x小2 小时前
[C#]——接口与继承
开发语言·c++·c#
微三云 - 廖会灵 (私域系统开发)3 小时前
企业私域商城系统架构选型分析:单体模板VS微服务自研架构
微服务·架构·系统架构
颜x小16 小时前
[C#] C++与c#语法对比
开发语言·c++·c#
weixin_4236521317 小时前
C#使用JObject
开发语言·c#