Steeltoe之Config用戶端篇

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.