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


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

1、創建三個CoreApi

        我們在項目中創建三個站點分別為 UserServices “用戶服務OrderServices “訂單服務” 以及 StorehouseServices “庫房服務”

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

     

   2、選擇項目模板

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

   

 

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

   

 

   3、在創建CoreApi的時候盡量不使用項目模板進行創建因為默認會使用MVC的引擎可以使用空模板進行創建,自行搭建。

2、CoreApi進行環境的配置

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

  項目創建后我們在項目啟動文件中有兩種環境啟動設置如下圖

   

  我們可以看到不論是使用IIS啟動還是 命令啟動時都默認使用開發環境變量“”Development“”。

  在項目創建完成后默認有一個Json的配置文件,我們打開后可以看到一個默認的名為 appsettings.Development.json 的配置文件 如圖所示

   

 

  也就是說項目創建完成后不論使用哪種環境運行都是同一個環境變量“Development” 同樣也代表這不論哪種環境運行默認使用的同一份配置文件

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

         2.1、如圖所示:

  

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

   

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

    3.1、首先使用IIS運行 默認走開發者配置

    

    3.2、在當前目錄 下使用dotnet run  運行

    

    我們可以看到配置已經生效了

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

    

    可以看到這個時候怎么的配置失效了因為命令行是托管在Kestrel上運行的默認使用的端口就是 5000/5001 這個時候我們需要在增加一個配置來更改默認

    

    配置如下步驟:

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

    

    配置 127.0.0.1:代表着localhost 在下面使用的時候需要進行一下轉換所以用127.0.0.1 具體配置如下

     在項目Program 中這樣去使用

    

    這里不會影響我們的其他運行方式因為運行的環境不同:運行結果如下     

     

  4、根據不同的運行環境讀取使用不同的配置文件

  上面的有的步驟只是更改了項目啟動時的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

  5、項目啟動后把服務注冊到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 配置博客 https://www.cnblogs.com/szlblog/p/8068311.html

3、消費consul中的CoreApi的服務

  1、創建項目

  使用什么樣的客戶端都行,控制台,MVC,WebFrom 都行

  2、具體代碼

  這個代碼只是用來引路,可以根據自己的喜好去進行封裝

  代碼如下:

 #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

有不足之處 希望大家指出相互學習,

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM