在 Asp. Net Core中使用 Ocelot 构建 API 网关

简介

在本文中, 您将学习一种使用 asp. net Core 中的 Ocelot 构建 API 网关的简单方法。也许你会问这个问题, 什么是 API 网关。
让我们先看看下面的截图。


5833359-730defac2e68eb19.png
网关

API 网关是我们系统的入口。它包含很多东西, 如路由、身份验证、服务发现、日志记录等。

Ocelot

Ocelot主要应用在.net微服务架构中,提供服务的统一的入口。您可以访问此项目的 Github 主页, 以查找更多信息。
下面我将用一个简单的示例展示Ocelot的使用方法。

第一步

首先创建三个项目

项目名称 类型 描述
APIGateway ASP.NET Core Empty 服务的入口
CustomersAPIServices ASP.NET Core Web API 处理关于顾客相关的API
ProductsAPIServices ASP.NET Core Web API 处理产品相关的API
5833359-450e3485dc6870f2.png
解决方案

第二步

先完成两个API服务,CustimersAPIServices项目中创建CustomersController。

    [Route("api/[controller]")]  
    public class CustomersController : Controller  
    {          
        [HttpGet]  
        public IEnumerable<string> Get()  
        {  
            return new string[] { "Catcher Wong", "James Li" };  
        }  
      
        [HttpGet("{id}")]  
        public string Get(int id)  
        {  
            return $"Catcher Wong - {id}";  
        }              
    }  

为了指定此服务的应用程序 URL, 我们应该在类Program中添加 UseUrls。

public static IWebHost BuildWebHost(string[] args) =>  
        WebHost.CreateDefaultBuilder(args)  
            .UseStartup<Startup>()  
            .UseUrls("http://localhost:9001")  
            .Build();

在ProductsAPIServices 项目中创建ProductsController


    [Route("api/[controller]")]  
    public class ProductsController : Controller  
    {  
        [HttpGet]  
        public IEnumerable<string> Get()  
        {  
            return new string[] { "Surface Book 2", "Mac Book Pro" };  
        }  
    }  

编辑类Program,也添加 UseUrls。

public static IWebHost BuildWebHost(string[] args) =>  
        WebHost.CreateDefaultBuilder(args)  
            .UseStartup<Startup>()  
            .UseUrls("http://localhost:9002")  
            .Build(); 

第三步

运行顾客服务和产品服务
开启两个终端,分别运行 dotnet run启动

5833359-96442c787768a3c9.png
两个终端

正如你看到的,顾客相关服务监听在 http://localhost:9001,产品相关服务监听在 http://localhost:9002

开启浏览器,检查服务是否正常


5833359-20bfb18efcd29490.png
浏览器

一切正常

第四步

现在我们再转向APIGateway项目。首先要安装Ocelot 程序集。
Install-Package Ocelot
安装好以后,发现Ocelot引用了很多程序集

5833359-35183c702676c6c3.png
引用

第五步

添加一个configuration.json文件

    {  
        "ReRoutes": [  
            {  
                "DownstreamPathTemplate": "/api/customers",  
                "DownstreamScheme": "http",  
                "DownstreamHost": "localhost",  
                "DownstreamPort": 9001,  
                "UpstreamPathTemplate": "/customers",  
                "UpstreamHttpMethod": [ "Get" ]  
            },  
            {  
                "DownstreamPathTemplate": "/api/customers/{id}",  
                "DownstreamScheme": "http",  
                "DownstreamHost": "localhost",  
                "DownstreamPort": 9001,  
                "UpstreamPathTemplate": "/customers/{id}",  
                "UpstreamHttpMethod": [ "Get" ]  
            },  
            {  
                "DownstreamPathTemplate": "/api/products",  
                "DownstreamScheme": "http",  
                "DownstreamPort": 9002,  
                "DownstreamHost": "localhost",  
                "UpstreamPathTemplate": "/api/products",  
                "UpstreamHttpMethod": [ "Get" ]  
            }  
        ],  
        "GlobalConfiguration": {  
            "RequestIdKey": "OcRequestId",  
            "AdministrationPath": "/administration"  
        }  
    }  

这个文件是API网关的配置文件。主要包含两个部分ReRoutes 和GlobalConfiguration。
ReRoutes 配置Ocelot 对请求的路由,Global configuration是一些通用配置。
用下面的例子简单介绍一下


    {  
        "DownstreamPathTemplate": "/api/customers/{id}",  
        "DownstreamScheme": "http",  
        "DownstreamHost": "localhost",  
        "DownstreamPort": 9001,  
        "UpstreamPathTemplate": "/customers/{id}",  
        "UpstreamHttpMethod": [ "Get" ]  
    }  

以Downstream开头的部分是说明请求要导航到http://localhost:9001/api/customers/{id}
以Upstream 开头的部分表示需要HTTP GET方法访问/customers/{id}的请求

第六步

编辑类Startup ,项目中启用Ocelot


    public class Startup  
    {  
        public Startup(IHostingEnvironment env)  
        {  
            var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();  
            builder.SetBasePath(env.ContentRootPath)      
                   //add configuration.json  
                   .AddJsonFile("configuration.json", optional: false, reloadOnChange: true)  
                   .AddEnvironmentVariables();  
      
            Configuration = builder.Build();  
        }  
      
        //change  
        public IConfigurationRoot Configuration { get; }  
      
        public void ConfigureServices(IServiceCollection services)  
        {  
            Action<ConfigurationBuilderCachePart> settings = (x) =>  
            {  
                x.WithMicrosoftLogging(log =>  
                {  
                    log.AddConsole(LogLevel.Debug);  
      
                }).WithDictionaryHandle();  
            };  
            services.AddOcelot(Configuration, settings);  
        }  
          
        //don't use Task here  
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env)  
        {  
            await app.UseOcelot();  
        }  
    }  

不要忘记在配置中增加configuration.json

第七步

API网关项目设置为监听地址:http://localhost:9000

第八步

运行API网关


5833359-f418763fd1d27ce4.gif
apigateway.gif

访问 http://localhost:9000/api/products ,其实请求结果来自http://localhost:9002/api/products
访问http://localhost:9000/customers,其实请求结果来自http://localhost:9001/api/customers

总结

本章总结了使用Ocelot创建API网关的方法,希望对你有帮助。
另外,这只是一个简单的示例,还有很多重要的环节没有提及,比如服务发现,授权和服务质量。

摘自Building API Gateway Using Ocelot In ASP.NET Core
参考ocelot中文文档
参考 .NET Core微服务之基于Ocelot+IdentityServer实现统一验证与授权

猜你喜欢

转载自blog.csdn.net/weixin_34399060/article/details/90964948