当前位置:主页 > 查看内容

ASP.NET Core Api网关Ocelot初探

发布时间:2021-04-18 00:00| 位朋友查看

简介:本文转载自微信公众号「UP技术控」,作者conan5566。转载本文请联系UP技术控公众号。 概述 Ocelot面向使用.NET运行微型服务/面向服务的体系结构的人员,这些体系结构需要在系统中具有统一的入口点。特别是我想与IdentityServer参考和承载令牌轻松集成。Ocelo……

本文转载自微信公众号「UP技术控」,作者conan5566。转载本文请联系UP技术控公众号。 

 概述

Ocelot面向使用.NET运行微型服务/面向服务的体系结构的人员,这些体系结构需要在系统中具有统一的入口点。特别是我想与IdentityServer参考和承载令牌轻松集成。Ocelot是按特定顺序排列的一堆中间件。Ocelot将HttpRequest对象操作到由其配置指定的状态,直到到达请求构建器中间件,在该中间件中它创建一个HttpRequestMessage对象,该对象用于向下游服务发出请求。发出请求的中间件是Ocelot管道中的最后一件事。它不会调用下一个中间件。有一块中间件可将HttpResponseMessage映射到HttpResponse对象,然后将其返回给客户端。基本上,它具有许多其他功能。

代码实现

1、新建api客户端1

2、新建api 网关test

3、nuget安装Ocelot

4、Program文件添加ConfigureAppConfiguration

  1. public class Program 
  2.     { 
  3.         public static void Main(string[] args) 
  4.         { 
  5.             CreateHostBuilder(args).Build().Run(); 
  6.         } 
  7.  
  8.         public static IHostBuilder CreateHostBuilder(string[] args) => 
  9.             Host.CreateDefaultBuilder(args) 
  10.             .ConfigureAppConfiguration(conf => 
  11.             { 
  12.                 conf.AddJsonFile("ocelot.json"falsetrue); 
  13.             }) 
  14.                 .ConfigureWebHostDefaults(webBuilder => 
  15.                 { 
  16.                     webBuilder.UseStartup<Startup>(); 
  17.                 }); 
  18.     } 

5、Startup文件配置

  1. services.AddOcelot(Configuration); 
  2.  
  3. app.UseOcelot().Wait(); 

6、网关项目下添加文件ocelot.json

  1.   "ReRoutes": [ 
  2.     { 
  3.       "DownstreamPathTemplate""/api/WeatherForecast/GetList"
  4.       "DownstreamScheme""http"
  5.       "DownstreamHostAndPorts": [ 
  6.         { 
  7.           "Host""localhost"
  8.           "Port": 5000 
  9.         } 
  10.       ], 
  11.       "UpstreamPathTemplate""/GetList"
  12.       "UpstreamHttpMethod": [ "Get" ] 
  13.     }, 
  14.  
  15.     { 
  16.       "DownstreamPathTemplate""/{everything}"
  17.       "DownstreamScheme""http"
  18.       "DownstreamHostAndPorts": [ 
  19.         { 
  20.           "Host""localhost"
  21.           "Port": 5000 
  22.         } 
  23.       ], 
  24.       "UpstreamPathTemplate""/{everything}"
  25.       "UpstreamHttpMethod": [ "Post" ] 
  26.     }, 
  27.     { 
  28.       "DownstreamPathTemplate""/api/WeatherForecast/GetModel?id={s1}"
  29.       "DownstreamScheme""http"
  30.       "DownstreamHostAndPorts": [ 
  31.         { 
  32.           "Host""localhost"
  33.           "Port": 5000 
  34.         } 
  35.       ], 
  36.       "UpstreamPathTemplate""/GetModel?id={s1}"
  37.       "UpstreamHttpMethod": [ "Get" ] 
  38.     } 
  39.   ] 

7、2个项目运行,测试

代码地址

https://gitee.com/conanOpenSource_admin/Example/commit/b3b5a6b15a060b46c5ecd2ea31f0d36791cda18c


本文转载自网络,原文链接:https://mp.weixin.qq.com/s/vs-FCxIvLbGVF5QCITadsA
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文

  • 周排行
  • 月排行
  • 总排行

随机推荐