The API Gateway Pattern is a design pattern used in microservices architecture. It acts as a single entry point for clients, managing all interactions between them and the backend services. This pattern simplifies client interactions by encapsulating the complexities of multiple microservices, providing features like request routing, load balancing, caching, and security.
Why Use an API Gateway?
- Centralized Entry Point: Clients interact with one endpoint rather than multiple services.
- Decoupling of Client and Services: The gateway handles communication with services, hiding service details from clients.
- Cross-cutting Concerns: It manages functionalities like authentication, logging, rate-limiting, etc., across services.
- Load Balancing: Distributes incoming traffic efficiently to backend services.
- Security: Acts as a gatekeeper, providing security features like SSL termination and token validation.
Introduction to Ocelot
Ocelot is an open-source API Gateway, designed for microservice architecture. This is based on .NET Core. Ocelot is a set of middleware designed for features such as routing, caching, security, rate limiting, etc. please refer to the link for more details.
Create Simple Services
Let's build a simple API Gateway using ASP.NET Core.We will be creating two simple services for demo purposes.Let us start two services – one is Product Service and another one is Customer Service
Setting up APIsProduct Service will looks like below-
using Microsoft.AspNetCore.Mvc; using models = Product.MicroService.Models; namespace Product.MicroService.Controllers { [ApiController] [Route("api/[controller]")] public class ProductController : ControllerBase { [HttpGet] public IActionResult GetAll() { var products = new List<models.Product> { new models.Product { Id = 1, ProductName = "Iphone", Rate = 2000 }, new models.Product { Id = 2, ProductName = "Samsung Galaxy", Rate = 1800 } }; return Ok(products); } } }
Customer Service will looks like below-
using Microsoft.AspNetCore.Mvc; using models = Customer.MicroService.Models; namespace Customer.MicroService.Controllers { [ApiController] [Route("api/[controller]")] public class CustomerController : ControllerBase { [HttpGet] public IActionResult GetAll() { var customers = new List<models.Customer> { new models.Customer {Id = 1, Name = "Manish", Email = "test@gmail.com"}, new models.Customer{Id = 2, Name = "Ashis", Email = "xyz@gmail.com" } }; return Ok(customers); } } }
Let us go ahead and create an empty ASP.NET Core project. And then install the Ocelot package.
Install-Package OcelotConfigure Ocelot
We need to create a JSON file – ocelot.json at the root project level in Gateway project.Let us modify the file and configure the Ocelot.json file
{ "GlobalConfiguration": { "BaseUrl": "http://localhost:5003" }, "Routes": [ { "UpstreamPathTemplate": "/gateway/product", "UpstreamHttpMethod": [ "Get" ], "DownstreamPathTemplate": "/api/product", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5160 } ] }, { "UpstreamPathTemplate": "/gateway/customer", "UpstreamHttpMethod": [ "Get" ], "DownstreamPathTemplate": "/api/customer", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5173 } ] } ] }
This configuration maps incoming requests to specific downstream services:
- /gateway/product will forward requests to the Product service running on localhost:5160.
- /gateway/customer will forward requests to the Customer service running on localhost:5173.
Now we need to configure our project to use the ocelot.json fine. These configuration needs to be done in Program.cs file as below,
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); builder.Services.AddOcelot(builder.Configuration);
The namespaces which need to be imported are,
using Ocelot.DependencyInjection; using Ocelot.Middleware;
Now add the Ocelot Middleware in Program.cs
await app.UseOcelot();
As a final step, to run all the services simultaneously, right click on Solution and select Properties, update the below highlighted settings.
Now instead of executing the downstream service, let us go ahead and execute the gateway and see the result.Execute the below Gateway end points and see whether we are getting the expected result
/gateway/product
/gateway/customer
Conclusion
The API Gateway Pattern helps manage complex microservice architectures by providing a unified interface for clients, simplifying the communication between clients and services. Using tools like Ocelot in .NET makes it straightforward to implement an API Gateway that handles routing, security, and load balancing efficiently.
This example is a basic introduction. In a production environment, you would also implement additional features like authentication, rate-limiting, logging, and more.
The full source code is available here:
Happy coding!! 😊
No comments:
Post a Comment