.net core使用ocelot---第七篇 服務發現


簡介

  .net core使用ocelot---第一篇 簡單使用  
  .net core使用ocelot---第二篇 身份驗證使用 
  .net core使用ocelot---第三篇 日志記錄 
  .net core使用ocelot---第四篇 限流熔斷 
  .net core使用ocelot---第五篇 服務質量 
  .net core使用ocelot---第六篇 負載均衡 

         本文我們介紹用Spring Cloud Eureka Server介紹Ocelot的服務發現模塊。

什么是服務發現

服務發現是自動檢測這些設備在計算機網絡上提供的設備和服務。服務發現協議(SDP)是幫助完成服務發現的網絡協議。服務發現旨在減少用戶的配置工作。

在Ocelot中我們可以使用許多的服務發現,比如Consul, Eureka等等。本文我使用Eureka進行介紹。Ocelot使用Steeltoe與Eureka進行通信,Eureka是一個開源項目,使.NET開發人員能夠在雲上構建彈性微服務時能實現滿足行業標准的最佳實踐。

我將使用Ocelot的7.1.0-unstable0011版本向您展示此功能。

Step1

         首先創建兩個API服務,一個是默認的ASP.NET Core Web API項目。在API網關發現我們的API服務之前,我們需要在Eureka服務上注冊。

         在appsettings.json添加一些配置

1.    "spring": {  
2.        "application": {  
3.            "name": "service-a"  
4.        }  
5.    },  
6.    "eureka": {  
7.        "client": {  
8.            "serviceUrl": "http://192.168.0.107:8761/eureka/",  
9.            "shouldFetchRegistry": true,  
10.            "validateCertificates": false  
11.        },  
12.        "instance": {  
13.            "port": 9001,  
14.            "instanceId": "192.168.0.103:9001",  
15.            "hostName": "192.168.0.103",  
16.            "healthCheckUrlPath": "/api/values/healthcheck",  
17.            "statusPageUrlPath": "/api/values/info"                  
18.        }  
19.    }  

注意

  1. Service-a 是Ocelot發現服務的重要標志。
  2. ServiceUrl是Eureka Server的端點。
  3. 獲得更多信息,看這里

  添加服務發現必要的代碼

public class Startup  
{  
    public Startup(IConfiguration configuration)  
    {  
        Configuration = configuration;  
    }  
  
    public IConfiguration Configuration { get; }  
  
    public void ConfigureServices(IServiceCollection services)  
    {  
        services.AddDiscoveryClient(Configuration);  
        services.AddMvc();  
    }  
  
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
    {  
        if (env.IsDevelopment())  
        {  
            app.UseDeveloperExceptionPage();  
        }  
  
        app.UseDiscoveryClient();  
        app.UseMvc();  
    }  
}  

  在這里,我將使用三個API服務來演示,兩個API服務名稱service-a具有不同的端口(9001和9003),一個API服務名稱service-b。

Step2

         新建一個APIGateway項目,添加名為ocelot.json的配置文件。

{  
    "ReRoutes": [  
        {  
            "DownstreamPathTemplate": "/api/values",  
            "DownstreamScheme": "http",  
            "UpstreamPathTemplate": "/a",  
            "UseServiceDiscovery": true,  
            "ServiceName": "service-a",  
            "UpstreamHttpMethod": [ "Get" ],  
            "QoSOptions": {  
                "ExceptionsAllowedBeforeBreaking": 3,  
                "DurationOfBreak": 1000,  
                "TimeoutValue": 5000  
            },  
            "FileCacheOptions": { "TtlSeconds": 15 },  
            "LoadBalancerOptions": {  
                "Type": "RoundRobin"  
            }  
        },  
        {  
            "DownstreamPathTemplate": "/api/values",  
            "DownstreamScheme": "http",  
            "UpstreamPathTemplate": "/b",  
            "UseServiceDiscovery": true,  
            "ServiceName": "service-b",  
            "UpstreamHttpMethod": [ "Get" ],  
            "QoSOptions": {  
                "ExceptionsAllowedBeforeBreaking": 3,  
                "DurationOfBreak": 1000,  
                "TimeoutValue": 5000  
            },  
            "FileCacheOptions": { "TtlSeconds": 15 }  
        }  
    ],  
    "GlobalConfiguration": {  
        "RequestIdKey": "OcRequestId",  
        "AdministrationPath": "/administration",  
        "ServiceDiscoveryProvider": { "Type": "Eureka" }  
    }  
}  

  這里有幾點需要注意。

  對於ReRoutes

  1. 將UseServiceDiscovery設為true。
  2. 將ServiceName值設為在API服務里定義的服務名稱。
  3. 不用指明DownstreamHostAndPorts的值。
  4. 將LoadBalancerOptions設成RoundRobin。

  對於GlobalConfiguration

         設置ServiceDiscoveryProvider的Type為Eureka。這是使用Eureka至關重要的配置。

         回到Program.cs,我們需要讓Ocelot可以使用。

public class Program  
{  
    public static void Main(string[] args)  
    {  
        BuildWebHost(args).Run();  
    }  
  
    public static IWebHost BuildWebHost(string[] args) =>  
        WebHost.CreateDefaultBuilder(args)  
           .UseUrls("http://*:9000")  
           .ConfigureAppConfiguration((hostingContext, config) =>  
            {  
                config  
                    .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)                        
                    .AddJsonFile("ocelot.json")  
                    .AddEnvironmentVariables();  
            })  
           .ConfigureServices(s =>  
            {  
                s.AddOcelot();  
            })  
            .Configure(a =>  
            {  
                a.UseOcelot().Wait();  
            })  
            .Build();  
}  

Step3

         讓Eureka跑起來。

  如你所見,Eureka服務啟動起來了,但是沒有可以使用的實例。

注意

         為了在你的電腦上跑Eureka服務,你可以按照下面的步驟嘗試。

  1. 安裝Java 8 的JDK
  2. 安裝Maven3.X
  3. 復制Spring Cloud Samples Eureka 代碼庫(https://github.com/spring-cloud-samples/eureka.git
  4. 轉到eureka服務的目錄(eureka)並使用mvn spring-boot:run啟動它

Step4

         我們如何注冊我們的服務?只需運行我們的項目,我們就會得到service-a實例。

         當運行我們的API服務,你就會發現service-a 運行在Eureka 服務里了

 

  好了,啟動我們的APIGateway,不幸的是,當我們運行起項目。

  查看異常信息,我們忘了在APIGateway項目中配置Eureka。在appsettings.json添加下面的配置。

"spring": {  
    "application": {  
        "name": "service-gw"  
    }  
},  
"eureka": {  
    "client": {  
"serviceUrl": "http://192.168.0.107:8761/eureka/",  
        "shouldRegisterWithEureka": false,  
        "validateCertificates": false  
    },  
    "instance": {  
        "port": 9000,  
        "instanceId": "192.168.0.103:9000",  
        "hostName": "192.168.0.103"  
    }  
}  

  重新啟動APIGateway,終於正常了。

  

  通過APIGat訪問service-a 

  通過APIGateway訪問未啟動的service-b

  毫無疑問我們不可能訪問service-b

  啟動后

  再次啟動

  最后注冊另一個service-a

  訪問service-a你得到的結果有時來自9001,有時來自9003 。因為我們負載均衡算法設為RoundRobin。

  當我們停止service-a的一個服務,我們依然可以訪問,但是終止的那個服務不能訪問。

  源碼在此

總結

         本文介紹了Ocelot使用Eureka實現服務發現的簡單示例。當讓還有consul也可以實現服務發現,下篇介紹。


免責聲明!

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



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