Steeltoe之Config客戶端篇
Steeltoe是一款開源項目,其目標是選取源自Netflix及其它公司的工具,使它們能夠運用於.NET社區。它不僅可以在.NET Core上,也可以在.NET Framework 4.X以上使用。此外,大多數的組件能夠同時運行在本地機器及Cloud Foundry(一個領先的雲應用平臺)之上。
Steeltoe基於Spring Cloud開發而成,它提供了數種類庫包使得.NET開發者可以利用這些工具實現一些通用模式(比如中心化配置管理,服務發現,斷路器等等),從而構建高度可擴展及具有彈性的分布式系統。通過Steeltoe,以及Spring Cloud,開發者能夠快速建立實現這些模式的微服務和應用程序。
本文將介紹Steeltoe中用於中心化配置管理的客戶端的組件。與之對應的Config Server是前文(初探Spring Cloud Config)中已經建立的。
ASP.NET Core應用
第一步,建立一個ASP.NET Core應用程序,可以使用空模板,然後手動添加Controller,View及appsettings.json文件和文件夾。
Package
想要使用這塊功能的組件,首先需要安裝對應的類庫。
對於ASP.NET Core,使用Steeltoe.Extensions.Configuration.ConfigServerCore
類庫。
對於Console/ASP.NET 4.x,使用Steeltoe.Extensions.Configuration.ConfigServerBase
Program.cs
在Program類中,利用IWebHostBuilder的擴展方法添加ConfigServer。
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.AddConfigServer()
.UseStartup<Startup>();
}
appsettings.json
在appsettings.json文件裏添加Config Server的URI地址。
{
"spring": {
"cloud": {
"config": {
"uri": "http://localhost:9555"
}
}
}
}
獲取配置
通過依賴註入方式,在Controller中得到Configuration,並從中取得message的值。這裏假設在Config Server的配置倉庫裏已經設置了message值為Hello, Steeltoe Configuration
。
public class HomeController : Controller
{
public IConfiguration Configuration { get; set; }
public HomeController(IConfiguration configuration)
{
Configuration = configuration;
}
public IActionResult Index()
{
ViewData["message"] = Configuration["message"];
return View();
}
}
顯示配置
在cshtml頁面中顯示message值。
@{
ViewData["Title"] = "Home";
}
@ViewData["message"]
結果
先啟動Spring Cloud的Config Server,再啟動上面的.NET Core代碼,結果如下:
Steeltoe之Config客戶端篇