.Net Core 2.2 ile Ocelot Api Gateway

Bugün sizlerle .Net Core 2.2 ve Ocelot kullanarak ufak bir örnek yapacağız. Öncelikle API Gateway nedir diyorsanız buradan ilgili posta ulaşabilirsiniz. Bu bana yetmedi biraz daha incelemek istiyorum diyenler burayı inceleyebilir.

Ocelot nedir?

Ocelot open-source bir .Net Core Api Gateway dir. Gatewayler bize kısaca,
Routing – Yönlendirme,
Authorisation – Yetki,
Caching – Önbellekten yararlanarak performans artışı ,
Logging– Loglama mekanizması ile kayıt tutma,
Configuration – Merkezi konfigurasyonlar,
Rate Limiting – Trafik hızının kontrolü,
Centralized Error Management – Merkezi hata yönetimi gibi alanlarda kolaylıklar sağlamaktadır.

eShopOnContainers architecture with API Gateways
eShopOnContainers architecture with API Gateways

Microsoft’un sitesinde de görebileceğiniz gibi eShopOnContainers mimarisinde ilgili mikro servislere yönlendirmeler için Ocelot’dan faydalanılmıştır.

Bugünkü senaryomuzda gelen isteği Ocelot üzerinden (API Gateway) karşılayacak ve ilgili servise yönlendireceğiz. Yani bir noktadan istek yapacağız Gateway arka tarafta ilgili servise yönlendirme yaparak bize response dönecek.

Hadi başlayalım;

Öncelikle Vs Code ve .Net Core Cli kullanacağım. Dosya yapısı aşağıdaki gibi olacak şekilde 3 adet .net core web api projesi oluşturacağım.

Ocelot-Gateway-with-.Net-Core
-TeamApi
-SportApi
-ApiGateway

mkdir Ocelot-Gateway-with-.Net-Core

(Bulunduğum dizinde Ocelot-Gateway-with-.Net-Core adında bir dosya oluşturuyorum. Benim örneğimi kapsayacak ana klasörüm olacak.)

cd Ocelot-Gateway-with-.Net-Core

(Oluşturduğum dosyanın içerisine giriyorum.)

dotnet new webapi -o TeamApi

( Ocelot-Gateway-with-.Net-Core dosyası içerinde TeamAPi adlı bir klasör içerisine aynı isimde bir web api oluşturuyorum. -o parametresi buna yarıyor)

dotnet new webapi -o SportApi
dotnet new webapi -o ApiGateway

Şimdi TeamApi ve SportApi içerisine girerek örnek kayıtlar döndüren endpoint ile beraber uygulamarın çalışcağı portları ayarlayalım.

TeamApi

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace TeamApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TeamController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "Beşiktaş", "Juventus" };
        }
    }
}
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace TeamApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://localhost:3000")
                .UseStartup<Startup>();
    }
}

SportApi

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace SportApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SportController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "Soccer", "Basketball" };
        }
    }
}
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace SportApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://localhost:2000")
                .UseStartup<Startup>();
    }
}

Şimdi ApiGateway projemize geçerek aşağıdaki komut ile ilgili nuget paketini yükleyelim. 13.5.2 versiyonunu kuracağım.

ApiGateway

Install-Package Ocelot

(Vs code için ctrl+shift+p ile Nuget Package Manager (eklenti) add seçeneği de kullanılabilir,. Visual Studio için ise Manage Nuget Package den yararlanılabilir yada “dotnet add package Ocelot” komutu kullanılabilir.)

dotnet restore

ApiGateway projemize ocelot.json dosyasını ekleyelim. Yönlendirmeyi buradaki konfigürasyona göre yapacağız. Konfigürasyon ayarlarını yapmadan önce Program.cs ve Startup.cs değişikliklerini yapalım.

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;

namespace ApiGateway
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((host, config) =>
            {
                config.AddJsonFile("ocelot.json");
            })
                .UseUrls("http://localhost:1000")
                .UseStartup<Startup>();
    }
}
       public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddOcelot(Configuration);
        }
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
            await app.UseOcelot();
        }

Şimdi sıra geldi ocelot.json dosyamızın konfigürasyonuna…

{
    "ReRoutes": [
        {
            "DownstreamPathTemplate": "/api/team",  
            "DownstreamScheme": "http",
            "DownstreamHostAndPorts":[{
                "Host":"localhost",
                "Port":3000
            }],                        
            "UpstreamPathTemplate": "/team-service/team"             
        },
        {
            "DownstreamPathTemplate": "/api/sport",  
            "DownstreamScheme": "http",
            "DownstreamHostAndPorts":[{
                "Host":"localhost",
                "Port":2000
            }],                        
            "UpstreamPathTemplate": "/sport-service/sport"      
        }
    ],
    "GlobalConfiguration": {
        "BaseUrl": "http://localhost:1000"
    }
}

Burada;

GlobalConfiguration kısmında gatewayin urli,

DownstreamPathTemplate ilgili servisteki route,

DownstreamHostAndPorts ilgili servisin host bilgileri,

UpstreamPathTemplate kullanıcının Gateway üzerinden geleceği route belirtilir.

Evet arkadaşlar örneğimizi tamamladık. Şimdi 3 uygulamamızı da çalıştırarak , postman üzerinden test edelim.

dotnet run

(Uygulamamızı çalıştırmak için kullanıyoruz.)

Ocelot Gateway ve NetCore
Ocelot Gateway ve NetCore

Umarım herkes için faydalı olmuştur. Hepinize iyi tatiller.

Github URL => https://github.com/EnesAys/Ocelot-Gateway-with-.Net-Core

Ocelot Repo Link => https://github.com/ThreeMammals/Ocelot

Kaynak
https://medium.com/devopsturkiye/net-core-microservice-api-gateway-9c28f988bc52
https://ocelot.readthedocs.io/en/latest/introduction/gettingstarted.html
https://docs.microsoft.com/tr-tr/dotnet/architecture/microservices/multi-container-microservice-net-applications/implement-api-gateways-with-ocelot

Written By

Bir önceki günden daha iyi olmak için çalışarak kendimi geliştirmek, öğrendiklerim ve öğreneceklerim ile yazılım sektöründe büyük ölçekli ve uluslararası projelerde kendimden söz ettirmek istiyorum.

More From Author

You May Also Like

Leave a Reply

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir