通过 Ocelot 实现 API 网关
API 网关
API网关是一个服务器,是系统的唯一入口,为每个客户端提供一个定制的API。它可能还具有其它职责,如身份验证、监控、负载均衡、缓存、请求分片与管理、静态响应处理。
Ocelot
Ocelot是一个用 .Net Core 实现并且开源的API网关,它功能强大,包括了:路由、请求聚合、服务发现、认证、鉴权、限流熔断、并内置了负载均衡器与Service Fabric、Butterfly Tracing集成。
安装依赖
Install-Package Ocelot
创建 Gateway.API
Startup.cs
中 配置如下
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseOcelot();
}
- 在 Gateway.API 中新建名为
Ocelot.json
的json配置文件
具体配置项请参照官方文档配置
{
"Routes": [
/*
## User.API
用户服务
*/
{
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
"DownstreamPathTemplate": "/api/user",
"UpstreamPathTemplate": "/user",
"UpstreamHttpMethod": [ "Get" ]
//"AuthenticationOptions": {
// "AuthenticationProviderKey": "finbook",
// "AllowedScopes": []
//}
},
/*
## Contacts.API
通讯录服务
*/
{
//获取联系人信息
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5003
}
],
"DownstreamPathTemplate": "/api/contacts",
"UpstreamPathTemplate": "/contacts",
"UpstreamHttpMethod": [ "Get" ]
},
{
//给联系人打标签
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5003
}
],
"DownstreamPathTemplate": "/api/contacts/tags",
"UpstreamPathTemplate": "/contacts/tags",
"UpstreamHttpMethod": [ "Put" ]
},
{
//好友申请(添加,通过,获取)
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5003
}
],
"DownstreamPathTemplate": "/api/contacts/apply-request",
"UpstreamPathTemplate": "/contacts/apply-request",
"UpstreamHttpMethod": [ "Get", "Post", "Put" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5000"
}
}
Program.cs
中配置如下
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config=> {
config
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile("Ocelot.json");
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
调试
-
启动两个API
-
【Gateway.API】:http://localhost:5000/contacts
-
【Contact.API】:http://localhost:5003/api/contacts
实际上在地址栏中请求上游地址 http://localhost:5000/contacts
时ocelot
会帮我们转发到配置的下游地址http://localhost:5003/api/contacts
以上一个简单的网关即搭建完成了
- 在地址栏请求