天天看點

在.NET Core中用最原生的方式讀取Nacos的配置

在.NET Core中用最原生的方式讀取Nacos的配置

背景

之前老黃寫過一篇《ASP.NET Core結合Nacos來完成配置管理和服務發現》簡單介紹了如何讓.NET Core程式接入Nacos,之前的SDK裡面更多的是對Nacos的Open API進行了封裝以及對服務注冊和發現的封裝。

配置這一塊當時并沒有過多的處理,用起來有時感覺不會特别順手,是以将它和.NET Core的配置結合起來了,讓它用起來更簡便。

怎麼個簡便法呢?

可以說,除了多添加一下provider,其他的操作都是和最原始的一模一樣,你想用IConfiguration就用IConfiguration,想用IOptions系列就用IOptions系列。

更容易做到無縫遷移!

當然,這個SDK出自老黃的手,難免會有一些坑和bug,這個就請各位多多包涵!!

前提條件

啟動Nacos Server

最簡單的方式,用docker啟動一個單機版的。

docker-compose -f example/standalone-mysql-8.yaml up

建立一個.NET Core項目,并安裝相應nuget包

這裡将用ASP.NET Core Web Api做示例,同時要安裝下面的nuget包

dotnet add package nacos-sdk-csharp-unofficial.Extensions.Configuration --version 0.2.6

更直接點,直接修改csproj

<PackageReference Include="nacos-sdk-csharp-unofficial.Extensions.Configuration" Version="0.2.6" />           

進行配置

打開Program.cs,在CreateHostBuilder加入Nacos的provider配置,都是Nacos的一些基礎配置。

public static IHostBuilder CreateHostBuilder(string[] args) =>

Host.CreateDefaultBuilder(args)
         .ConfigureAppConfiguration((context, builder) =>
         {
             var c = builder.Build();
             var dataId = c.GetValue<string>("nacosconfig:DataId");
             var group = c.GetValue<string>("nacosconfig:Group");
             var tenant = c.GetValue<string>("nacosconfig:Tenant");
             var optional = c.GetValue<bool>("nacosconfig:Optional");
             var serverAddresses = c.GetSection("nacosconfig:ServerAddresses").Get<List<string>>();
                           
             // 0.2.6版本之前,隻支援這種方式
             builder.AddNacosConfiguration(x =>
             {
                 x.DataId = dataId;
                 x.Group = group;
                 x.Tenant = tenant;
                 x.Optional = optional;
                 x.ServerAddresses = serverAddresses;
             });

             //// 0.2.6版本之後可以從配置檔案讀取Nacos的基本配置
             //builder.AddNacosConfiguration(c.GetSection("nacosconfig"));
             
         })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });           

同樣的,我們還要修改appsettings.json,把Nacos的配置寫進去,主要是用來區分不同環境的配置來源。

{

"Logging": {

"LogLevel": {
    "Default": "Warning",
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime" :"Information"
}             

},

"nacosconfig":{

"Optional": false,
"DataId": "msconfigapp",
"Group": "",
"Tenant": "ca31c37e-478c-46ed-b7ea-d0ebaa080221",
"ServerAddresses": ["localhost:8848"]           

}

好了,到這裡,用于配置Nacos相關的内容就結束了。接下來,要做的就是在nacos控制台進行配置的維護。

配置使用

建立一個配置

添加一個對應的實體類

public class AppSettings

public string Str { get; set; }

public int Num { get; set; }

public List<int> Arr { get; set; }

public SubObj SubObj { get; set; }           

public class SubObj

public string a { get; set; }           

因為要驗證IOptions模式,是以要在Startup中加點代碼

public void ConfigureServices(IServiceCollection services)

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddControllers();           

下面就是真正的使用了!

[ApiController]

[Route("api/[controller]")]

public class ConfigController : ControllerBase

private readonly IConfiguration _configuration;
private readonly AppSettings _settings;
private readonly AppSettings _sSettings;
private readonly AppSettings _mSettings;

public ConfigController(
    IConfiguration configuration,
    IOptions<AppSettings> options,
    IOptionsSnapshot<AppSettings> sOptions,
    IOptionsMonitor<AppSettings> _mOptions
    )
{
    _configuration = configuration;
    _settings = options.Value;
    _sSettings = sOptions.Value;
    _mSettings = _mOptions.CurrentValue;
}

[HttpGet]
public string Get()
{
    string id = Guid.NewGuid().ToString("N");

    Console.WriteLine($"============== begin {id} =====================");

    var conn = _configuration.GetConnectionString("Default");
    Console.WriteLine($"{id} conn = {conn}");

    var version = _configuration["version"];
    Console.WriteLine($"{id} version = {version}");

    var str1 = Newtonsoft.Json.JsonConvert.SerializeObject(_settings);
    Console.WriteLine($"{id} IOptions = {str1}");

    var str2 = Newtonsoft.Json.JsonConvert.SerializeObject(_sSettings);
    Console.WriteLine($"{id} IOptionsSnapshot = {str2}");

    var str3 = Newtonsoft.Json.JsonConvert.SerializeObject(_mSettings);
    Console.WriteLine($"{id} IOptionsMonitor = {str3}");

    Console.WriteLine($"===============================================");

    return "ok";
}           

從上面的代碼,看上去應該熟悉的不能再熟悉了吧!這些配置的用法,就是.NET Core裡面提供的最原始的,原汁原味。

啟動通路這個接口,可以看到下面的輸出。

在控制台修改這個配置。

再次通路,可以發現,除了IOptions之外,都讀取到了新的配置。

之是以IOptions沒有擷取到最新的配置,那是因為它的預設實作不會進行更新操作,也就是從啟動到結束,它都是不會變的。

在有配置變更的情景,請盡可能不要用IOptions,用IOptionsSnapshot和IOptionsMonitor來替代!

總結

這裡介紹了如何讓.NET Core更容易對接Nacos配置的方法,希望對各位有所幫助。

如果您對 nacos-sdk-charp 這個項目感興趣,也歡迎一起開發和維護這個項目。

本文首發于我的公衆号:不才老黃

感興趣的可以關注一下。

如果您認為這篇文章還不錯或者有所收獲,可以點選右下角的【推薦】按鈕,因為你的支援是我繼續寫作,分享的最大動力!

作者:Catcher ( 黃文清 )

來源:

http://catcher1994.cnblogs.com/