文章目录
前言
API网关是访问你系统的入口,它包括很多东西,比如路由(Routing),身份验证(Authentication),服务发现(Service discovery),日志(Logging ),等等,本文简单入门Ocelot
提示:以下是本篇文章正文内容,下面案例可供参考,项目环境.NET Core 3.1
一、Ocelot是什么?
原文地址:https://ocelot.readthedocs.io/en/latest/introduction/bigpicture.html#
Ocelot是用.net Core实现的一款开源的网关,Ocelot其实就是一组按照顺序排列的.net core中间件。它接受到请求之后用request builder构建一个HttpRequestMessage对象并发送到下游服务,当下游请求返回到Ocelot管道时再由一个中间件将HttpRequestMessage映射到HttpResponse上返回客户端。
二、使用步骤
1.解决方案下新建一个StudyAPIGateway项目

2.安装NuGet软件包
代码如下(示例):
Install-Package Ocelot

3.项目下创建Config文件下,在创建configuration.json文件

configuration.json内容如下(示例):
{
"Routes": [
{
//网关转发到下游格式
"DownstreamPathTemplate": "/WeatherForecast/gets",
"DownstreamScheme": "http",
//下游服务配置
"DownstreamHostAndPorts": [
{
//下游地址
"Host": "localhost",
//下游端口号
"Port": 9001
}
],
//上游Api请求格式
"UpstreamPathTemplate": "/todos",
//上下游支持请求方法
"UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ]
},
{
"DownstreamPathTemplate": "/WeatherForecast/gets",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 9002
}
],
"UpstreamPathTemplate": "/todoss",
"UpstreamHttpMethod": [ "Get" ]
}
]
}
4.修改Program类
Programd代码如下(示例) 注 ip和 port都从运行控制台获取 :
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
String ip = config["ip"];
String port = config["port"];
webBuilder
.UseStartup<Startup>()
.UseUrls($"http://{ip}:{port}")
;
});
}
5.修改Startup类
Startup代码如下(示例):
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot(new ConfigurationBuilder()
.AddJsonFile("Config/configuration.json")
.Build());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseOcelot();
}
}
6.编译网关项目,运行
-
运行命令(示例):
dotnet StudyAPIGateway.dll --ip 127.0.0.1 --port 8001
2.Postman中通过网关进行服务访问 访问地址:http://127.0.0.1:8001/todos


本文介绍Ocelot——一款基于.NET Core的开源API网关,并提供了一个简单的使用指南,包括安装配置步骤及如何实现基本的路由功能。

2555

被折叠的 条评论
为什么被折叠?



