背景
之前老黃寫(xiě)過(guò)一篇《ASP.NET Core結(jié)合Nacos來(lái)完成配置管理和服務(wù)發(fā)現(xiàn)》簡(jiǎn)單介紹了如何讓.NET
Core程序接入Nacos,之前的SDK里面更多的是對(duì)Nacos的Open API進(jìn)行了封裝以及對(duì)服務(wù)注冊(cè)和發(fā)現(xiàn)的封裝。
配置這一塊當(dāng)時(shí)并沒(méi)有過(guò)多的處理,用起來(lái)有時(shí)感覺(jué)不會(huì)特別順手,所以將它和.NET Core的配置結(jié)合起來(lái)了,讓它用起來(lái)更簡(jiǎn)便。
怎么個(gè)簡(jiǎn)便法呢?
可以說(shuō),除了多添加一下provider,其他的操作都是和最原始的一模一樣,你想用IConfiguration就用IConfiguration,想用
IOptions系列就用IOptions系列。
更容易做到無(wú)縫遷移!
當(dāng)然,這個(gè)SDK出自老黃的手,難免會(huì)有一些坑和bug,這個(gè)就請(qǐng)各位多多包涵!!
前提條件
* 啟動(dòng)Nacos Server
最簡(jiǎn)單的方式,用docker啟動(dòng)一個(gè)單機(jī)版的。
docker-compose -f example/standalone-mysql-8.yaml up
* 創(chuàng)建一個(gè).NET Core項(xiàng)目,并安裝相應(yīng)nuget包
這里將用ASP.NET Core Web Api做示例,同時(shí)要安裝下面的nuget包
dotnet add package nacos-sdk-csharp-unofficial.Extensions.Configuration
--version 0.2.6
更直接點(diǎn),直接修改csproj
<ItemGroup> <PackageReference
Include="nacos-sdk-csharp-unofficial.Extensions.Configuration" Version="0.2.6"
/> </ItemGroup>
進(jìn)行配置
打開(kāi)Program.cs,在CreateHostBuilder加入Nacos的provider配置,都是Nacos的一些基礎(chǔ)配置。
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的配置寫(xiě)進(jìn)去,主要是用來(lái)區(qū)分不同環(huán)境的配置來(lái)源。
{ "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相關(guān)的內(nèi)容就結(jié)束了。接下來(lái),要做的就是在nacos控制臺(tái)進(jìn)行配置的維護(hù)。
配置使用
新建一個(gè)配置
添加一個(gè)對(duì)應(yīng)的實(shí)體類
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; } }
因?yàn)橐?yàn)證IOptions模式,所以要在Startup中加點(diǎn)代碼
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"; } }
從上面的代碼,看上去應(yīng)該熟悉的不能再熟悉了吧!這些配置的用法,就是.NET Core里面提供的最原始的,原汁原味。
啟動(dòng)訪問(wèn)這個(gè)接口,可以看到下面的輸出。
在控制臺(tái)修改這個(gè)配置。
再次訪問(wèn),可以發(fā)現(xiàn),除了IOptions之外,都讀取到了新的配置。
之所以IOptions沒(méi)有獲取到最新的配置,那是因?yàn)樗哪J(rèn)實(shí)現(xiàn)不會(huì)進(jìn)行更新操作,也就是從啟動(dòng)到結(jié)束,它都是不會(huì)變的。
在有配置變更的情景,請(qǐng)盡可能不要用IOptions,用IOptionsSnapshot和IOptionsMonitor來(lái)替代!
總結(jié)
這里介紹了如何讓.NET Core更容易對(duì)接Nacos配置的方法,希望對(duì)各位有所幫助。
如果您對(duì) nacos-sdk-charp 這個(gè)項(xiàng)目感興趣,也歡迎一起開(kāi)發(fā)和維護(hù)這個(gè)項(xiàng)目。
本文首發(fā)于我的公眾號(hào):不才老黃
感興趣的可以關(guān)注一下。
熱門(mén)工具 換一換
