Asp.Net5 WebAPI 使用NacOS作为配置中心的方法

自建Nacos的方法请看官方的教程:

https://nacos.io/zh-cn/docs/quick-start.html

搭建好后,添加配置信息。

.NetCore的组件的git地址:https://github.com/nacos-group/nacos-sdk-csharp

操作说明:https://nacos-sdk-csharp.readthedocs.io/en/latest/introduction/gettingstarted.html

一、引用2个组件:

nacos-sdk-csharp.AspNetCore

nacos-sdk-csharp.Extensions.Configuration

二、配置文件appsettings.json

{
  "NacosConfig": {
    "Listeners": [
      {
        "Optional": false,
        "DataId": "common",
        "Group": "DEFAULT_GROUP" 
      },
      {
        "Optional": false,
        "DataId": "demo",
        "Group": "DEFAULT_GROUP" 
      }
    ],
    "Namespace": "public",
    "ServerAddresses": [ "http://10.10.1.90:8848/" ],
    "UserName": "nacos",
    "Password": "nacos",
    "ConfigUseRpc": false,
    "NamingUseRpc": false
  }
 

}

注意:

1、必须要有 ConfigUseRpc和NamingUseRpc这2个参数,若用的是http协议,则都是false ,若用grpc协议则为true.(这个官方提供的demo没有写,就会报错)

2、Listeners 对应配置文件。DataId是配置名称,Tenant是命名空间名称。Group组名。

3、ServerAddresses是Nacos的服务器地址,可以添加多个。

4、若是新的命名空间,则 Namespace对应的是命名空间的Id.

5、Listeners里添加的配置文件一定要存在,不要有多余的节点,可以少,但是不可以多。Group也不能填错。

  

(这个组件的日志不知道怎么打印出来,谁教一下)

三、program里添加代码

Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, builder) =>
            {

                var c = builder.Build();
                builder.AddNacosV2Configuration(c.GetSection("NacosConfig"));
            })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

主要是添加了ConfigureAppConfiguration这里的代码,就是将Nacos的添加的配置文件读取出来,并且支持热更新。

四、使用

跟.NetCore自带的读取配置文件的方法一致。

比如 :

[ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
         
        private readonly ILogger<WeatherForecastController> _logger; 
        private readonly IConfiguration _configuration; 


        public WeatherForecastController(IConfiguration configuration, ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
            _configuration =  configuration;
        }

        [HttpGet]
        public string  Get()
        {
            var test = _configuration.GetValue<string>("ConnectionStrings:redis");
            return test;
        }
    }
原文地址:https://www.cnblogs.com/puzi0315/p/15577888.html