日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

《ASP.NET Core 微服务实战》-- 读书笔记(第9章)

發布時間:2023/12/4 asp.net 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 《ASP.NET Core 微服务实战》-- 读书笔记(第9章) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

第 9 章 微服務系統的配置

微服務系統中的配置需要關注更多其他方面的因素,包括:

  • 配置值的安全讀寫

  • 值變更的審計能力

  • 配置信息源本身的韌性和可靠性

  • 少量的環境變量難以承載大型、復雜的配置信息

  • 應用要決定是否支持配置值的在線更新和實時變更,還要決定如何實現

  • 對功能開關和層級化設置的支持

  • 對敏感信息以及加密密鑰本身進行存儲和讀取支持

本章首先討論在應用中使用環境變量的機制,并演示 Docker 的支持情況

接著探索一個來自 Netflix OSS 技術棧的配置服務器產品

最后將運用 etcd,它是一個常用于配置管理的開源分布式鍵值數據庫

在 Docker 中使用環境變量

為配置提供默認值時,還應該考慮哪些設置在應用啟動期間需要通過環境變量進行覆蓋

為配置設置值時,可使用鍵值對顯示指定,如下所示:

$ sudo docker run -e SOME_VAR='foo' \ -e PASSWORD='foo' \ -e USER='bar' \ -e DB_NAME='mydb' \ -p 3000:3000 \ --name container_name microservices-aspnetcore/image:tag

或者,如果不希望在命令行中顯示傳入值,也可以把來自啟動環境的環境變量轉發到容器內部,只要不傳入包含值的等式即可,例如:

$ docker run -e PORT -e CLIENTSCRET -e CLIENTKEY [...]

這一命令將把命令行所在終端中的 PORT、CLIENTSECRET 和 CLIENTKEY 環境變量的值傳入 Docker 容器中,在這個過程中它們的值不會在命令行文本中公開,以防范潛在的安全漏洞和敏感信息泄露

如果需要向容器傳入大量的環境變量,可以向 docker 命令指定一個包含鍵值對列表的文件:

$ docker run --env-file ./myenv.file [...]

使用 Spring Cloud 配置服務器

圍繞服務的配置管理的最大難題之一,并非如何將值注入到環境變量,而在于這些值本身的日常維護

當配置的原始源處的值發生變更時,我們如何得到通知

更進一步,當值發生變更時,我們如何回溯并查看之前的值

你可能發現,這似乎可用使用類似于 Git 倉庫的方法來管理配置值

Spring Cloud 配置服務器(SCCS)的開發人員也持相同看法

要在 .NET Core 應用中添加 SCCS 客戶端的支持,只需要在項目中添加對 Steeltoe.Extensions.Configuration.ConfigServer NuGet 包的引用

接著,我們需要配置應用,讓它從正確的位置獲取設置信息

我們需要定義一個 Spring 應用名稱,并在 appsettings.json 文件中添加配置服務器的 URL

{"spring": {"application": {"name": "foo"},"cloud": {"config": {"uri": "http://localhost:8888"}}},"Logging": {"IncludeScopes": false,"LogLevel": {"Default": "Debug","System": "Information","Microsoft": "Information"}} }

配置完成后,Startup 構造方法仍然與其他應用幾乎一致

public Startup(IHostingEnvironment env) {var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile("appsettings.json", optional: true, reloadOnChange: false).AddEnvironmentVariables().AddConfigServer(env);Configuration = builder.Build(); }

要添加對配置服務器的支持,接下來需要修改 ConfigureServices 方法

首先調用 AddConfigServer 向依賴注入子系統加入配置客戶端

接著指定泛型參數并調用 Configure 方法

這一操作能把從配置服務器獲取的配置信息包裝為一個 IOptionsSnapshot 對象,然后可由控制器和其他代碼使用

public void ConfigureServices(IServiceCollection services) {services.AddConfigServer(Configuration);services.AddMvc();services.Configure<ConfigServerData>(Configuration); }

此處,用于表示從配置服務器獲取的數據的數據模型,是基于 Spring Cloud 服務器示例倉庫中的示例配置進行建模的

public class ConfigServerData {public string Bar { get; set; }public string Foo { get; set; }public Info Info { get; set; } }public class Info {public string Description { get; set; }public string Url { get; set; } }

然后,在需要時,就可注入這個類的實例,以及配置服務器的客戶端參數

public class MyController : MyController {private IOptionsSnapshot<ConfigServerData> MyConfiguration { get; set; }private ConfigServerClientSettingsOptions ConfigServerClientSettingsOptions { get; set; }public MyController(IOptionsSnapShot<ConfigServerData> opts, IOptions<ConfigServerClientSettingsOptions> clientOpts){...}... }

上述配備完成后,如果配置服務器已處于運行狀態,構造器中的 opts 變量將包含應用所有的相關配置

啟動配置服務器最簡單的方法就是直接通過 Docker 鏡像運行以下代碼

$ docker run -p 8888:8888 \ -e SPRING_CLOUD_CONFIG_SERVER_GET_URI=http://github.com/spring-cloud-samples/ \config-repohyness/spring-cloud-config-server

如果服務器運行正確,應該能通過以下命令獲取配置信息

curl http://localhost:8888/foo/development

在本地用 Docker 鏡像啟動配置服務器后,使用上面展示的 C# 代碼,就能體驗將外部配置數據提供給 .NET Core 微服務的過程

使用 etcd 配置微服務

Spring Cloud 配置服務器的替代品不計其數,etcd 是其中很流行的一個

上一章簡單提到,etcd 是一個輕量級的分布式鍵值數據庫

它就是為你存儲分布式系統所需要的最關鍵信息的位置

etcd 是一個集群產品,其節點之間的通信是基于 Raft 共識算法實現的

etcd 的一個最常見運用場景就是存儲和檢索配置信息以及功能標志

在本章的例子里,我訪問 compose.io 并注冊了一個免費試用的托管 etcd

創建 etcd 配置提供程序

GitHub鏈接:https://github.com/microservices-aspnetcore/etcd-client

創建配置源

using System; using Microsoft.Extensions.Configuration;namespace ConfigClient {public class EtcdConfigurationSource : IConfigurationSource{public EtcdConnectionOptions Options { get; set; }public EtcdConfigurationSource(EtcdConnectionOptions options){this.Options = options;}public IConfigurationProvider Build(IConfigurationBuilder builder){return new EtcdConfigurationProvider(this);}} }

創建配置構建器

using System; using System.Collections.Generic; using EtcdNet; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Primitives;namespace ConfigClient {public class EtcdConfigurationProvider : ConfigurationProvider{private EtcdConfigurationSource source;public EtcdConfigurationProvider(EtcdConfigurationSource source){this.source = source;}public override void Load(){EtcdClientOpitions options = new EtcdClientOpitions(){Urls = source.Options.Urls,Username = source.Options.Username,Password = source.Options.Password,UseProxy = false,IgnoreCertificateError = true};EtcdClient etcdClient = new EtcdClient(options);try{EtcdResponse resp = etcdClient.GetNodeAsync(source.Options.RootKey,recursive: true, sorted: true).Result;if (resp.Node.Nodes != null){foreach (var node in resp.Node.Nodes){// child nodeData[node.Key] = node.Value;}}}catch (EtcdCommonException.KeyNotFound){// key does notConsole.WriteLine("key not found exception");}}} }

借助如下擴展方法

using Microsoft.Extensions.Configuration;namespace ConfigClient {public static class EtcdStaticExtensions{public static IConfigurationBuilder AddEtcdConfiguration(this IConfigurationBuilder builder,EtcdConnectionOptions connectionOptions){return builder.Add(new EtcdConfigurationSource(connectionOptions));}}public class EtcdConnectionOptions{public string[] Urls { get; set; }public string Username { get; set; }public string Password { get; set; }public string RootKey { get; set; }} }

便能在 Startup 類中把 etcd 添加為配置源

using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging;namespace ConfigClient {public class Startup{public Startup(IHostingEnvironment env){var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true).AddEtcdConfiguration(new EtcdConnectionOptions{Urls = new string[] {"https://portal1934-21.euphoric-etcd-31.capital-one-3.composedb.com:17174","https://portal2016-22.euphoric-etcd-31.capital-one-3.composedb.com:17174"},Username = "root",Password = "changeme",RootKey = "/myapp"}).AddEnvironmentVariables();Configuration = builder.Build();}public static IConfigurationRoot Configuration { get; set; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){// Add framework services.services.AddMvc();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){loggerFactory.AddConsole();loggerFactory.AddDebug();app.UseMvc();}} }

使用來自 etcd 的配置值

using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using EtcdNet; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration;namespace ConfigClient.Controllers {[Route("api/[controller]")]public class ValuesController : Controller{private ILogger logger;public ValuesController(ILogger<ValuesController> logger){this.logger = logger;}// GET api/values[HttpGet]public IEnumerable<string> Get(){List<string> values = new List<string>();values.Add(Startup.Configuration.GetSection("/myapp/hello").Value);values.Add(Startup.Configuration.GetSection("/myapp/rate").Value);return values;}// GET api/values/5[HttpGet("{id}")]public string Get(int id){return "value";}// POST api/values[HttpPost]public void Post([FromBody]string value){}// PUT api/values/5[HttpPut("{id}")]public void Put(int id, [FromBody]string value){}// DELETE api/values/5[HttpDelete("{id}")]public void Delete(int id){}} }

現在訪問 http://localhost:3000/api/values 端點,將返回這些值:

{"world", "12.5"}

這些正是本節前面面向 etcd 服務器添加的值

只使用了少數幾行代碼,我們便創建了一個由遠程配置服務器支持的、穩定而符合標準的 ASP.NET 配置源

總結

以上是生活随笔為你收集整理的《ASP.NET Core 微服务实战》-- 读书笔记(第9章)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。