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代碼,結果如下: