.net core+Spring Cloud學習之路 二


  前言:

  原本計划這次寫一下搭建eureka群集。但是發現上次寫的只是服務的注冊,忘了寫服務的發現,所以這次先把服務發現補上去。

  1.   我們基於上篇文章,再新建兩個.net core web api項目,分別起名為order_one,order_two, 作為兩個訂單服務。我們以order_one為例。
    1. 同理先使用nuget添加Pivotal.Discovery.ClientCore庫。
    2. Startup.cs 中添加
      1 public void ConfigureServices(IServiceCollection services)
      2         {
      3             // services.AddDiscoveryClient(Configuration);
      4             services.AddDiscoveryClient(Configuration);
      5             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
      6         }
       1 public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
       2         {
       3             loggerFactory.AddConsole(Configuration.GetSection("Logging"));
       4             loggerFactory.AddDebug();
       5             if (env.IsDevelopment())
       6             {
       7                 app.UseDeveloperExceptionPage();
       8             }
       9             else
      10             {
      11                 app.UseHsts();
      12             }
      13             app.UseDiscoveryClient();
      14             app.UseHttpsRedirection();
      15             app.UseMvc();
      16         }

      需要using Pivotal.Discovery.Client; 

    3. appsettings.json 添加eureka服務配置
      {
        "Logging": {
          "IncludeScopes": false,
          "Debug": {
            "LogLevel": {
              "Default": "Warning"
            }
          },
          "Console": {
            "LogLevel": {
              "Default": "Warning"
            }
          }
        },
        "spring": {
          "application": {
            "name": "order"
          }
        },
        "eureka": {
          "client": {
            "serviceUrl": "http://localhost:8888/eureka/",
            "shouldFetchRegistry": true
          },
          "instance": {
            "port": 5001,
            "hostName": "localhost"
          }
        }
      }

       

    4. 修改launchSettings.json 端口改為5001
      {
        "iisSettings": {
          "windowsAuthentication": false,
          "anonymousAuthentication": true,
          "iisExpress": {
            "applicationUrl": "http://localhost:5001/",
            "sslPort": 0
          }
        },
        "profiles": {
          "IIS Express": {
            "commandName": "IISExpress",
            "launchBrowser": true,
            "launchUrl": "api/values",
            "environmentVariables": {
              "ASPNETCORE_ENVIRONMENT": "Development"
            }
          },
          "Order_One": {
            "commandName": "Project",
            "launchBrowser": true,
            "launchUrl": "api/order",
            "environmentVariables": {
              "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "applicationUrl": "http://localhost:5001/"
          }
        }
      }

       

    5. 添加一個控制器,返回order one
      [Route("api")]
          public class ValuesController : Controller
          {
      
      
              // GET api/values
              [HttpGet("value")]
              public string Get()
              {
                  return "Order One";
              }
          }

       

    6. 再建一個同樣的項目,order_two
  2. 上述項目創建完成后,我們先啟動spring cloud項目。然后同時啟動三個.net core項目。這個時候我們刷新一下spring cloud頁面。

    這個時候發現名為order的有兩個服務。

  3. 修改一下orderserver的控制器代碼
    [Route("api")]
        public class ValuesController : Controller
        {
    
            DiscoveryHttpClientHandler _handler;
    
           
    
            private const string GET_SERVICES_URL = "http://order/api/value";
            private ILogger<ValuesController> _logger;
    
    
            public ValuesController(IDiscoveryClient client, ILoggerFactory logFactory = null)
            {
                _handler = new DiscoveryHttpClientHandler(client);
                _logger = logFactory?.CreateLogger<ValuesController>();
            }
    
            [HttpGet("order")]
            public async Task<string> GetServices()
            {
                _logger?.LogInformation("GetServices");
                var client = GetClient();
                return await client.GetStringAsync(GET_SERVICES_URL);
    
            }
    
            private HttpClient GetClient()
            {
                var client = new HttpClient(_handler, false);
                return client;
            }
    
        }

    然后再次啟動這三個.net core項目,並訪問http://localhost:5000/api/order,如圖,他成功返回了order two,多刷新幾次會發現返回的order One 和 order two是來回變的。

    說明eureka服務中心幫我們實現了負載均衡。

     

  4. 這個時候,我們可以把order_one 或者 order_two關掉一個。我們再次訪問http://localhost:5000/api/order會出現一次錯誤,然后eureka會自動把有問題的服務踢掉(時間可配置),再次訪問不再有問題。

參考資料:

Spring Cloud

Steeltoe

總結

現在網絡上類似這樣的文章很多,自己再單獨寫一份就是為了做個筆記,跟各位大牛交流一下,自己也學習學習。


免責聲明!

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



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