AspNetCore 多環境配置 以及註冊 消費Consul

本文主要記錄 CoreApi 的多環境配置以及如何消費在consul中註冊的Api 服務

一、建立三個CoreApi

        咱們在項目中建立三個站點分別爲 UserServices 「用戶服務OrderServices 「訂單服務」 以及 StorehouseServices 「庫房服務」html

  1. 、打開VS2017 建立Core Web 應用程序

     

   2、選擇項目模板

       注意:在選擇項目模板的時候有一個支持Https 的選項不使用能夠去掉json

   

 

  忘記去掉了也沒問題在項目屬性調試中也能夠去掉 以下圖:api

   

 

   三、在建立CoreApi的時候儘可能不使用項目模板進行建立由於默認會使用MVC的引擎可使用空模板進行建立,自行搭建。

二、CoreApi進行環境的配置

  1、CoreApi的幾種環境:開發(Development)佔存(Staging)生產(Production)

  項目建立後咱們在項目啓動文件中有兩種環境啓動設置以下圖服務器

   

  咱們能夠看到不管是使用IIS啓動仍是 命令啓動時都默認使用開發環境變量「」Development「」。app

  在項目建立完成後默認有一個Json的配置文件,咱們打開後能夠看到一個默認的名爲 appsettings.Development.json 的配置文件 如圖所示負載均衡

   

 

  也就是說項目建立完成後不論使用哪一種環境運行都是同一個環境變量「Development」 一樣也表明這不論哪一種環境運行默認使用的同一份配置文件異步

  二、新增Production(生產)環境配置文件

         2.一、如圖所示:ide

  

  2.2、更改launchSettings.json 中的環境變量的配置信息 以下性能

   

  三、運行結果 三種運行方式

    3.一、首先使用IIS運行 默認走開發者配置學習

    

    3.二、在當前目錄 下使用dotnet run  運行

    

    咱們能夠看到配置已經生效了

    (3):在項目的生成bin 目錄下使用 dotnet  WebApplication1.dll 運行 結果

    

    能夠看到這個時候怎麼的配置失效了由於命令行是託管在Kestrel上運行的默認使用的端口就是 5000/5001 這個時候咱們須要在增長一個配置來更改默認

    

    配置以下步驟:

    在項目新增的配置文件appsettings.Production.json中 添加 以下

    

    配置 127.0.0.1:表明着localhost 在下面使用的時候須要進行一下轉換因此用127.0.0.1 具體配置以下

     在項目Program 中這樣去使用

    

    這裏不會影響咱們的其餘運行方式由於運行的環境不一樣:運行結果以下     

     

  四、根據不一樣的運行環境讀取使用不一樣的配置文件

  上面的有的步驟只是更改了項目啓動時的IP端口信息,下面咱們配置在項目運行時根據不一樣的運行環境去讀取不一樣的配置文件

  Startup 文件寫入以下代碼

 private IHostingEnvironment env;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="environment"></param>
        public Startup(IHostingEnvironment environment)
        {
            env = environment;
            if (env.IsDevelopment())
            {
                var config = new ConfigurationBuilder()
                 .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.Development.json", true, true) //.AddJsonFile("appsettings.json", true, true) //
                 .AddEnvironmentVariables()
                 .Build();
                Configuration = config;
            }
            //生產環境Production運行 命令運行讀取的配置信息
            if (env.IsProduction())
            {
                var config = new ConfigurationBuilder()
                 .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                 .AddJsonFile("appsettings.Production.json", true, true)
                 .AddEnvironmentVariables()
                 .Build();
                Configuration = config;
            };
        }
View Code

  五、項目啓動後把服務註冊到Consul中

  代碼以下

  public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
       
            //ServiceID複製
            ConsulServicesID = Configuration["ServicesName"]+ Guid.NewGuid();
            using (var client = new ConsulClient(ConsulConfig))
            {
                //註冊服務到 Consul
                client.Agent.ServiceRegister(new AgentServiceRegistration()
                {
                    ID = ConsulServicesID,//服務編號,不能重複,用 Guid 最簡單
                    Name = Configuration["ServicesName"],//服務的名字
                    Address = Configuration["SerivceIP"],//個人 ip 地址(能夠被其餘應用訪問的地址,本地測試能夠用127.0.0.1,機房環境中必定要寫本身的內網 ip 地址)
                    Port = Convert.ToInt32(Configuration["SerivcePort"]),//個人端口
                    Check = new AgentServiceCheck
                    {
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服務中止多久後反註冊
                        Interval = TimeSpan.FromSeconds(10),//健康檢查時間間隔,或者稱爲心跳間隔
                        HTTP = $"{Configuration["HealthUrl"]}/api/Health",//健康檢查地址
                        Timeout = TimeSpan.FromSeconds(5)
                    }
                }).Wait();//Consult 客戶端的全部方法幾乎都是異步方法,可是都沒按照規範加上Async 後綴,因此容易誤導。記得調用後要 Wait()或者 await

            }
            //程序正常退出的時候從 Consul 註銷服務
            //要經過方法參數注入 IApplicationLifetime
            applicationLifetime.ApplicationStopped.Register(() =>
            {
                using (var client = new ConsulClient(ConsulConfig))
                {
                    //ServiceDeregister異步方法增長 Wait 等待完成
                    client.Agent.ServiceDeregister(ConsulServicesID).Wait();
                }
            });
        }
View Code

  6、項目中我使用了Swagger 具體配置

            Swagger 配置博客 http://www.javashuo.com/article/p-exanjcem-kz.html

三、消費consul中的CoreApi的服務

  一、建立項目

  使用什麼樣的客戶端都行,控制檯,MVC,WebFrom 都行

  二、具體代碼

  這個代碼只是用來引路,能夠根據本身的喜愛去進行封裝

  代碼以下:

 #region //查看全部consul中被註冊的服務
            //查看全部consul中被註冊的服務
            using (var consulClient = new ConsulClient(c => { c.Address = new Uri("http://127.0.0.1:8500"); c.Datacenter = "dc1"; }))
            {

                var services = consulClient.Agent.Services().Result.Response;
                //var ss = services.Values.Where(s => s.Service.Equals("UserServices", StringComparison.OrdinalIgnoreCase));//忽略大小寫
                foreach (var service in services.Values)
                {
                    Console.WriteLine($"id={service.ID},name={service.Service},ip={service.Address},port={service.Port}");
                }
            }
            #endregion
            #region 客戶端負載均衡
            //客戶端負載均衡
            using (var consulClient = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500")))
            {
                var services = consulClient.Agent.Services().Result.Response.Values
                .Where(s => s.Service.Equals("UserServices", StringComparison.OrdinalIgnoreCase));
                if (!services.Any())
                {
                    Console.WriteLine("找不到服務的實例");
                }
                else
                {
                    // services.ElementAt(1);//若是環境中有多臺服務器註冊服務時咱們可使用隨機數的方式,使用下標進行隨機抽取一臺服務進行使用
                    //集羣中也能夠輪訓,當服務器性能差很少的時候能夠輪着來
                    var service = services.ElementAt(Environment.TickCount % services.Count());
                    Console.WriteLine($"{service.Address}:{service.Port}");
                }

            }
            #endregion

            #region 調用服務方法     UserServices/api/Values
            using (var consulClient = new ConsulClient(c => { c.Address = new Uri("http://127.0.0.1:8500"); c.Datacenter = "dc1"; }))
            {
                var AllServicesInfor = consulClient.Agent.Services().Result.Response;
                //獲取第一個實例 把UserServices轉換爲在Consul中註冊的路徑 而後進行訪問
                var UserServices = AllServicesInfor.Values.Where(s => s.Service.Equals("UserServices", StringComparison.OrdinalIgnoreCase)).First();//忽略大小寫
                using (System.Net.Http.HttpClient http = new HttpClient())
                {
                    using (var HttpContent = new StringContent("", System.Text.Encoding.UTF8, "application/json"))
                    {
                        var ss = http.PostAsync($"http://{UserServices.Address}:{UserServices.Port}/api/Values", HttpContent);
                        string sss = ss.Result.RequestMessage.ToString();
                    }
                }
            }
            #endregion
View Code

 項目連接

 連接:https://pan.baidu.com/s/1V0YcX1kFJg752icNICTuQQ 密碼:1s47

有不足之處 但願你們指出相互學習,

                                     本文原創:轉載請註明出處 謝謝!

相關文章
相關標籤/搜索