. NET Core play Ocelot API gateway

Keywords: JSON github

These years have been really tough at home. Www.68mn. Many choose to change careers. But after. net Core is open-source across platforms. Community ecology is slowly building up. Go for the good. It's good news for developers who stick to the. NET front.  

In particular, Microsoft acquired $7.5 billion of GitHub. . net ecological community circle. There is bound to be an increase. The development trend is getting better and better. (of course, this is just my personal wish)

I'm lazy recently. I haven't written an article for a while. But the pursuit of new technology and the desire to learn will never stop

Recently, microservices have been hot. Large projects can be divided into smaller independent projects according to business. Easy to manage and collaborate with each other

 

What is Ocelot

Ocelot is an open-source API gateway implemented with. NET Core. It has powerful functions, including routing, request aggregation, service discovery, authentication, authentication, current limiting and fusing. It also has built-in load balancer integrated with Service Fabric and Butterfly Tracing. These functions only need simple configuration to complete

 

But there are still limited articles about Ocelot on the Internet.  

First of all, thank you for the article by Ocelot

https://www.cnblogs.com/shanyou/p/7787183.html(Zhang Youyi)

https://www.cnblogs.com/Leo_wl/p/7852311.html (HackerVirus God)

https://www.cnblogs.com/jesse2013/p/net-core-apigateway-ocelot-docs.html(Take off( Jesse) God)

 

First, create a new. NET Core Api with VS2017

 

1.NuGet console installation Ocelot

PM> Install-Package Ocelot

 

2. In the project Startup.cs modify

Two important namespaces are needed here

using Ocelot.DependencyInjection;
using Ocelot.Middleware;

public Startup(IHostingEnvironment environment)
        {
            var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();
            builder.SetBasePath(environment.ContentRootPath)
                   .AddJsonFile("appsettings.json", false, reloadOnChange: true)
                   .AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: false, reloadOnChange: true)
                   .AddJsonFile("configuration.json", optional: false, reloadOnChange: true)
                   .AddEnvironmentVariables();


            Configuration = builder.Build();
        }

 

/// <summary>
        ///to configure
        /// </summary>
        public IConfigurationRoot Configuration { get; }

        /// <summary>
        /// Configure services
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            Action<ConfigurationBuilderCachePart> settings = (x) =>
            {
                x.WithMicrosoftLogging(log =>
                {
                    log.AddConsole(LogLevel.Debug);

                }).WithDictionaryHandle();
            };
            services.AddOcelot(Configuration, settings);
            //services.AddMvc();
        }

 

/// <summary>
        /// to configure Ocelot
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            await app.UseOcelot();
            //app.UseMvc();
        }

 

Then the entry program Main

public static void Main(string[] args)
        {
            IWebHostBuilder builder = new WebHostBuilder();
            builder.ConfigureServices(s =>
            {
                s.AddSingleton(builder);
            });
            builder.UseKestrel()
                   .UseContentRoot(Directory.GetCurrentDirectory())
                   .UseIISIntegration()
                   .UseStartup<Startup>()
                   .UseApplicationInsights();
            var host = builder.Build();
            host.Run();
        }

 

3. Create a new Json file named configuration

Add configuration as follows

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/values",
      "DownstreamScheme": "http",
      "DownstreamHost": "localhost",
      "DownstreamPort": 1001,
      "UpstreamPathTemplate": "/api/values",
      "UpstreamHttpMethod": [ "Get" ],
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3,
        "DurationOfBreak": 10,
        "TimeoutValue": 5000
      },
      "HttpHandlerOptions": {
        "AllowAutoRedirect": false,
        "UseCookieContainer": false
      },
      "AuthenticationOptions": {

      }
    },
    {
      "DownstreamPathTemplate": "/api/product",
      "DownstreamScheme": "http",
      "DownstreamPort": 1002,
      "DownstreamHost": "localhost",
      "UpstreamPathTemplate": "/api/product",
      "UpstreamHttpMethod": [ "Get" ],
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3,
        "DurationOfBreak": 10,
        "TimeoutValue": 5000
      },
      "AuthenticationOptions": {

      }
    }
  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/admin"
  }
}

 

Then create two new APi projects

And set their port number to 1001 1002

 

Another similar

The above Json configuration reflects the mapping relationship between the upstream request and the downstream service. The upstream is the URL directly called by the client, and the downstream is the service corresponding to our development.

Then you can set up multi project startup or open a new instance separately

 

Next F5 start project

 

 

Finally, the source code address of Ocelot on GitHub is attached

https://github.com/TomPallister/Ocelot 

Posted by chokies12 on Fri, 19 Jun 2020 05:42:44 -0700