Ocelot (a) - .Net Core open source gateway

Ocelot - .Net Core open source gateway

Author: markjiang7m2
original address: https://www.cnblogs.com/markjiang7m2/p/10857688.html
Source Address: https://gitee.com/Sevenm2/OcelotDemo

Give you introduced today Ocelot is a service gateway based on open source projects WebAPI .net core, it's very powerful, including routing, aggregation request, the service found that certification authentication, current limiting, load balancing and other functions. These functions can be used directly by modifying the configuration file json, very convenient. Ocelot is a system of external exposure to a request for entry, all external interfaces must be to make requests to the API downstream through this gateway, as in the subway security system, everyone must go through security checks in order to take the subway.

I'm going to start one by one Ocelot's function is illustrated by specific cases, and cases involving the complete code in this article can all be downloaded from my code repository.

Ocelot project to build

By VS2017 based on .net core WebAPI create a new project, and then search through nuget direct Ocelotline to add a reference Ocelot or use the following command.

Install-Package Ocelot

Add in the root directory of a project .jsonconfiguration file, the file name of the custom, this case is Ocelot.json add configuration is as follows:

{
    "ReRoutes": [],
    "GlobalConfiguration": {
    }
}

You can see two configuration items included in our configuration file, ReRoutes is an array will contain routing server configuration, GlobalConfiguration is a global configuration items. I'll pass a variety of cases detailed in the specific configuration items and how to use the content in the following, therefore, here temporarily expand a description.
The configuration file is added to the .net core configuration
Program.cs

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, builder) => {
            builder.AddJsonFile("Ocelot.json");
        })
        .UseStartup<Startup>();

Because .net core support when the configuration file is modified reloaded, so if we need to reload the support can be modified as follows:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, builder) => {
            builder.AddJsonFile("Ocelot.json", optional: false, reloadOnChange: true);
        })
        .UseStartup<Startup>();

Ocelot will be registered as middleware, we need to add two namespaces
Startup.cs

using Ocelot.DependencyInjection;
using Ocelot.Middleware;
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddOcelot();
}

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

    app.UseMvc();
    app.UseOcelot().Wait();
}

At this point, our Ocelot has been set up is complete. We adopted the following specific examples to illustrate how to modify the configuration using related functions.

Configuration parameters introduced

We look first to understand what parameters, as well as the meaning of these parameters are included in the end. Earlier we have introduced to the configuration file contains two configuration items: ReRoutes and GlobalConfiguration.
Let's look at GlobalConfiguration, it is a global configuration item, usually we have to add an attribute in this configuration item BaseUrl, BaseUrl service Ocelot is exposed outside of Url.

"GlobalConfiguration": {
    "BaseUrl": "http://localhost:4727"
}

ReRoutes is an array, where each element represents a route, and a route contains all configuration parameters are as follows:

{
    "DownstreamPathTemplate": "/",
    "UpstreamPathTemplate": "/",
    "UpstreamHttpMethod": [
        "Get"
    ],
    "AddHeadersToRequest": {},
    "AddClaimsToRequest": {},
    "RouteClaimsRequirement": {},
    "AddQueriesToRequest": {},
    "RequestIdKey": "",
    "FileCacheOptions": {
        "TtlSeconds": 0,
        "Region": ""
    },
    "ReRouteIsCaseSensitive": false,
    "ServiceName": "",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [
        {
            "Host": "localhost",
            "Port": 8001,
        }
    ],
    "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 0,
        "DurationOfBreak": 0,
        "TimeoutValue": 0
    },
    "LoadBalancer": "",
    "RateLimitOptions": {
        "ClientWhitelist": [],
        "EnableRateLimiting": false,
        "Period": "",
        "PeriodTimespan": 0,
        "Limit": 0
    },
    "AuthenticationOptions": {
        "AuthenticationProviderKey": "",
        "AllowedScopes": []
    },
    "HttpHandlerOptions": {
        "AllowAutoRedirect": true,
        "UseCookieContainer": true,
        "UseTracing": true
    },
    "UseServiceDiscovery": false
}
  • Downstream Downstream Service Configuration
  • UpStream upstream service configuration
  • Aggregates Services Aggregation Configuration
  • ServiceName, LoadBalancer, UseServiceDiscovery configuration service discovery
  • AuthenticationOptions Authentication Service
  • RouteClaimsRequirement Claims Authentication Configuration
  • RateLimitOptions limiting configuration
  • FileCacheOptions cache configuration
  • QosOptions quality service and fuse configuration
  • DownstreamHeaderTransform header forwarding configuration

Of course, we do not need to set all parameters in actual use, only need to be configured according to actual needs.

Case by the way

Ocelot route is the most basic functions. Ocelot receiving a request from an upstream service has been validated, the service request is forwarded to the downstream, so we must first configure routing them on a downstream service parameters.

{
    "DownstreamPathTemplate": "/api/ocelot/{Id}",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [
            {
                "Host": "localhost",
                "Port": 8001,
            }
        ],
    "UpstreamPathTemplate": "/ocelot/{Id}",
    "UpstreamHttpMethod": ["Get"]
}
  • Url template downstream DownstreamPathTemplate request, {}the contents of the parameter representative of the dynamic
  • DownstreamScheme downstream services http scheme
  • Address DownstreamHostAndPorts downstream services, if LoadBalancer, then here you can fill in a number of
  • UpstreamPathTemplate upstream request is input by the user template Url
  • UpstreamHttpMethod upstream http request method, the array may be used

Thus, when the upstream to the service address http://localhost:4727/ocelot/5upon request, forwards the request to the downstream Ocelot service http://localhost:8001/api/ocelot/5.
This case provides downstream services Demo - OcelotDownAPI, will publish OcelotDownAPI to IIS port can be used. Downstream service returns a string after receiving a request to identify themselves.

[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
    var result = await Task.Run(() =>
    {
        return $"This is from {HttpContext.Request.Host.Value}, path: {HttpContext.Request.Path}";
    });
    return Ok(result);
}

Test Results:
Ocelot_001_routing1.png

If desired Ocelot to forward all requests, it may be configured as follows:

{
    "DownstreamPathTemplate": "/{url}",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [
            {
                "Host": "localhost",
                "Port": 8001,
            }
        ],
    "UpstreamPathTemplate": "/{url}",
    "UpstreamHttpMethod": ["Get"]
}

Get all this will be able to forward the request to downstream services. But the priority of this configuration is the lowest, once a match to the other routing template, will give priority to.

If desired Ocelot forward only a specific upstream service request from the Host, it can be configured as follows:

{
    "DownstreamPathTemplate": "/{url}",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [
            {
                "Host": "localhost",
                "Port": 8001,
            }
        ],
    "UpstreamPathTemplate": "/{url}",
    "UpstreamHttpMethod": ["Get"],
    "UpstreamHost": "localhost:4023"
}

Ocelot will only come from such forward localhost: 4023 request. Note that, if the configuration includes two other routes UpstreamHostare identical except for the routing, i.e., one with UpstreamHostand the other without, then with Ocelot prefers UpstreamHostroute.

Set the priority routes. We can define the ReRoutespriority routing array of responses. 0 is the lowest priority, the larger the number, the higher the priority.

[
{
    "UpstreamPathTemplate": "/ocelot/{Id}"
    "Priority": 0
},
{
    "UpstreamPathTemplate": "/ocelot/10"
    "Priority": 1
},
]

to sum up

This paper describes the Ocelot functionality and a simple case about how to build a basic application of the gateway, and Ocelot Ocelot's. Since Ocelot is very powerful, if all cases are placed in the same article will cause excessive length, not easy to read, so I will write a series of articles for the Ocelot function, we hope you continue to join.

References
cited herein in reference to the preparation process or part of the following article, if infringement, please contact modified or deleted.
https://www.cnblogs.com/jesse2013/p/net-core-apigateway-ocelot-docs.html

Ocelot - .Net Core open source gateway

Author: markjiang7m2
original address: https://www.cnblogs.com/markjiang7m2/p/10857688.html
Source Address: https://gitee.com/Sevenm2/OcelotDemo

Give you introduced today Ocelot is a service gateway based on open source projects WebAPI .net core, it's very powerful, including routing, aggregation request, the service found that certification authentication, current limiting, load balancing and other functions. These functions can be used directly by modifying the configuration file json, very convenient. Ocelot is a system of external exposure to a request for entry, all external interfaces must be to make requests to the API downstream through this gateway, as in the subway security system, everyone must go through security checks in order to take the subway.

I'm going to start one by one Ocelot's function is illustrated by specific cases, and cases involving the complete code in this article can all be downloaded from my code repository.

Ocelot project to build

By VS2017 based on .net core WebAPI create a new project, and then search through nuget direct Ocelotline to add a reference Ocelot or use the following command.

Install-Package Ocelot

Add in the root directory of a project .jsonconfiguration file, the file name of the custom, this case is Ocelot.json add configuration is as follows:

{
    "ReRoutes": [],
    "GlobalConfiguration": {
    }
}

You can see two configuration items included in our configuration file, ReRoutes is an array will contain routing server configuration, GlobalConfiguration is a global configuration items. I'll pass a variety of cases detailed in the specific configuration items and how to use the content in the following, therefore, here temporarily expand a description.
The configuration file is added to the .net core configuration
Program.cs

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, builder) => {
            builder.AddJsonFile("Ocelot.json");
        })
        .UseStartup<Startup>();

Because .net core support when the configuration file is modified reloaded, so if we need to reload the support can be modified as follows:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, builder) => {
            builder.AddJsonFile("Ocelot.json", optional: false, reloadOnChange: true);
        })
        .UseStartup<Startup>();

Ocelot will be registered as middleware, we need to add two namespaces
Startup.cs

using Ocelot.DependencyInjection;
using Ocelot.Middleware;
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddOcelot();
}

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

    app.UseMvc();
    app.UseOcelot().Wait();
}

At this point, our Ocelot has been set up is complete. We adopted the following specific examples to illustrate how to modify the configuration using related functions.

Configuration parameters introduced

We look first to understand what parameters, as well as the meaning of these parameters are included in the end. Earlier we have introduced to the configuration file contains two configuration items: ReRoutes and GlobalConfiguration.
Let's look at GlobalConfiguration, it is a global configuration item, usually we have to add an attribute in this configuration item BaseUrl, BaseUrl service Ocelot is exposed outside of Url.

"GlobalConfiguration": {
    "BaseUrl": "http://localhost:4727"
}

ReRoutes is an array, where each element represents a route, and a route contains all configuration parameters are as follows:

{
    "DownstreamPathTemplate": "/",
    "UpstreamPathTemplate": "/",
    "UpstreamHttpMethod": [
        "Get"
    ],
    "AddHeadersToRequest": {},
    "AddClaimsToRequest": {},
    "RouteClaimsRequirement": {},
    "AddQueriesToRequest": {},
    "RequestIdKey": "",
    "FileCacheOptions": {
        "TtlSeconds": 0,
        "Region": ""
    },
    "ReRouteIsCaseSensitive": false,
    "ServiceName": "",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [
        {
            "Host": "localhost",
            "Port": 8001,
        }
    ],
    "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 0,
        "DurationOfBreak": 0,
        "TimeoutValue": 0
    },
    "LoadBalancer": "",
    "RateLimitOptions": {
        "ClientWhitelist": [],
        "EnableRateLimiting": false,
        "Period": "",
        "PeriodTimespan": 0,
        "Limit": 0
    },
    "AuthenticationOptions": {
        "AuthenticationProviderKey": "",
        "AllowedScopes": []
    },
    "HttpHandlerOptions": {
        "AllowAutoRedirect": true,
        "UseCookieContainer": true,
        "UseTracing": true
    },
    "UseServiceDiscovery": false
}
  • Downstream Downstream Service Configuration
  • UpStream upstream service configuration
  • Aggregates Services Aggregation Configuration
  • ServiceName, LoadBalancer, UseServiceDiscovery configuration service discovery
  • AuthenticationOptions Authentication Service
  • RouteClaimsRequirement Claims Authentication Configuration
  • RateLimitOptions limiting configuration
  • FileCacheOptions cache configuration
  • QosOptions quality service and fuse configuration
  • DownstreamHeaderTransform header forwarding configuration

Of course, we do not need to set all parameters in actual use, only need to be configured according to actual needs.

Case by the way

Ocelot route is the most basic functions. Ocelot receiving a request from an upstream service has been validated, the service request is forwarded to the downstream, so we must first configure routing them on a downstream service parameters.

{
    "DownstreamPathTemplate": "/api/ocelot/{Id}",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [
            {
                "Host": "localhost",
                "Port": 8001,
            }
        ],
    "UpstreamPathTemplate": "/ocelot/{Id}",
    "UpstreamHttpMethod": ["Get"]
}
  • Url template downstream DownstreamPathTemplate request, {}the contents of the parameter representative of the dynamic
  • DownstreamScheme downstream services http scheme
  • Address DownstreamHostAndPorts downstream services, if LoadBalancer, then here you can fill in a number of
  • UpstreamPathTemplate upstream request is input by the user template Url
  • UpstreamHttpMethod upstream http request method, the array may be used

Thus, when the upstream to the service address http://localhost:4727/ocelot/5upon request, forwards the request to the downstream Ocelot service http://localhost:8001/api/ocelot/5.
This case provides downstream services Demo - OcelotDownAPI, will publish OcelotDownAPI to IIS port can be used. Downstream service returns a string after receiving a request to identify themselves.

[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
    var result = await Task.Run(() =>
    {
        return $"This is from {HttpContext.Request.Host.Value}, path: {HttpContext.Request.Path}";
    });
    return Ok(result);
}

Test Results:
Ocelot_001_routing1.png

If desired Ocelot to forward all requests, it may be configured as follows:

{
    "DownstreamPathTemplate": "/{url}",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [
            {
                "Host": "localhost",
                "Port": 8001,
            }
        ],
    "UpstreamPathTemplate": "/{url}",
    "UpstreamHttpMethod": ["Get"]
}

Get all this will be able to forward the request to downstream services. But the priority of this configuration is the lowest, once a match to the other routing template, will give priority to.

If desired Ocelot forward only a specific upstream service request from the Host, it can be configured as follows:

{
    "DownstreamPathTemplate": "/{url}",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [
            {
                "Host": "localhost",
                "Port": 8001,
            }
        ],
    "UpstreamPathTemplate": "/{url}",
    "UpstreamHttpMethod": ["Get"],
    "UpstreamHost": "localhost:4023"
}

Ocelot will only come from such forward localhost: 4023 request. Note that, if the configuration includes two other routes UpstreamHostare identical except for the routing, i.e., one with UpstreamHostand the other without, then with Ocelot prefers UpstreamHostroute.

Set the priority routes. We can define the ReRoutespriority routing array of responses. 0 is the lowest priority, the larger the number, the higher the priority.

[
{
    "UpstreamPathTemplate": "/ocelot/{Id}"
    "Priority": 0
},
{
    "UpstreamPathTemplate": "/ocelot/10"
    "Priority": 1
},
]

to sum up

This paper describes the Ocelot functionality and a simple case about how to build a basic application of the gateway, and Ocelot Ocelot's. Since Ocelot is very powerful, if all cases are placed in the same article will cause excessive length, not easy to read, so I will write a series of articles for the Ocelot function, we hope you continue to join.

References
cited herein in reference to the preparation process or part of the following article, if infringement, please contact modified or deleted.
https://www.cnblogs.com/jesse2013/p/net-core-apigateway-ocelot-docs.html

Guess you like

Origin www.cnblogs.com/letyouknowdotnet/p/10964484.html