. Net Core microservice gateway: ocelot integration and introduction

Posted by Gargouil on Sat, 06 Nov 2021 22:28:14 +0100

What is the gateway

In short, a gateway is a request entry exposed to the outside. Just like the doorman, people outside must pass through the doorman if they want to come in. Of course, the gateway is not necessarily necessary, and the back-end service can also provide services to the client through http. However, for complex and large-scale projects, the use of gateway has many advantages that cannot be abandoned, such as unified request aggregation to save traffic and reduce coupling, giving the project the ability to fuse and limit current, improving availability, and so on.

What is ocelot

ocelot is an open source api Gateway project implemented by. net core. Open source address: https://github.com/ThreeMammals/Ocelot

In addition to being very suitable for. net developers, ocelot has powerful functions, including routing, authentication, request aggregation, current limiting fuse, service discovery, authentication, built-in load balancer, Consul integration, etc.

Of course, there are more than one api gateway. There are also Kongs on the market. It's just as you like.

ocelot integration

First, make it clear that the gateway should exist as an independent process. Let's create a new. Net core 3.1 project, and then add the nuget package:

For version, select the latest version currently supported.

After adding the nuget package, you need to modify the StartUp:

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

            //if (env.IsDevelopment())
            //    app.UseDeveloperExceptionPage();




            //app.UseEndpoints(endpoints =>
            //    endpoints.MapControllers();

Don't be surprised here, because if you go through the gateway, you won't go through the default pipeline. UseOcelot().Wait() means to set all the middleware of ocelot, and ocelot also provides many libraries for integrating middleware, such as these:

Now, to make ocelot run successfully, you need to add a new configuration file and add a reference to the configuration file in the Program:

        public static IHostBuilder CreateHostBuilder(string[] args) =>
                .ConfigureAppConfiguration(config =>
                    config.AddJsonFile("ocelotConfig.json", optional: false, reloadOnChange: true);
                .ConfigureWebHostDefaults(webBuilder =>


  "Routes": [
      "DownstreamPathTemplate": "/{url}", //Service address--url variable
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
          "Host": "",
          "Port": 5050 //Service port
      "UpstreamPathTemplate": "/MJ/{url}", //default gateway --url variable
      "UpstreamHttpMethod": [ "Get", "Post" ]

This is a simple forwarding configuration. The configuration items beginning with Downstream and Upstream are Downstream and Upstream related items. In the microservice architecture, the client - server is usually understood as Upstream - Downstream, which can be replaced by itself.

The above configuration file does one thing: when receiving an upstream request, forward the request with [/ MJ / all] in the request path to the IP[ [all] and return the results. It supports HTTP get and post methods. In fact, this is the most basic routing.

To test, start the project and write the request path:

As you can see, ocelot successfully forwarded the local request to the remote server according to the routing rules, and sent back the results. The most basic functions of a gateway are.

The remote service requested in the screenshot is a project built based on consumer in my previous articles. If you are interested, you can have a look.

More advanced applications of Ocelot, such as fuse current limiting and identity authentication, are completed through configuration. I will sort them out and send them out. At the same time, I also suggest reading the official documents carefully. Address: https://ocelot.readthedocs.io/en/latest/

Topics: Microservices