以前老黃寫過一篇《ASP.NET Core結合Nacos來完成配置管理和服務發現》簡單介紹瞭如何讓.NET Core程序接入Nacos,以前的SDK裏面更多的是對Nacos的Open API進行了封裝以及對服務註冊和發現的封裝。mysql
配置這一塊當時並無過多的處理,用起來有時感受不會特別順手,因此將它和.NET Core的配置結合起來了,讓它用起來更簡便。web
怎麼個簡便法呢?sql
能夠說,除了多添加一下provider,其餘的操做都是和最原始的如出一轍,你想用IConfiguration
就用IConfiguration
,想用IOptions
系列就用IOptions
系列。docker
更容易作到無縫遷移!json
固然,這個SDK出自老黃的手,不免會有一些坑和bug,這個就請各位多多包涵!!api
最簡單的方式,用docker啓動一個單機版的。app
docker-compose -f example/standalone-mysql-8.yaml up
這裏將用ASP.NET Core Web Api作示例,同時要安裝下面的nuget包ide
dotnet add package nacos-sdk-csharp-unofficial.Extensions.Configuration --version 0.2.6
更直接點,直接修改csprojui
<ItemGroup> <PackageReference Include="nacos-sdk-csharp-unofficial.Extensions.Configuration" Version="0.2.6" /> </ItemGroup>
打開Program.cs
,在CreateHostBuilder
加入Nacos的provider配置,都是Nacos的一些基礎配置。3d
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 這個項目感興趣,也歡迎一塊兒開發和維護這個項目。
本文首發於個人公衆號:不才老黃
感興趣的能夠關注一下。