Asp.Net Core + Ocelot 网关搭建:路由简单配置

时间:2022-02-17 21:42:01

前言

  Ocelot是一个基于中间件的网关实现,功能有很多。从浅入深简单学习并记录一下吧。本篇就是一个简单的路由配置实现。

DEMO 搭建

  首先建立三个项目。Api.User,Api.Article,Api.GateWay.ApiGateWay项目中引入Ocelot Nuget包.添加配置文件Ocelot.json.

{
"ReRoutes": [
{
"DownstreamPathTemplate": "/{all}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 60001
}
],
"UpstreamPathTemplate": "/user/{all}",
"UpstreamHttpMethod": ["GET","POST"]
},
{
"DownstreamPathTemplate": "/{all}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 60002
}
],
"UpstreamPathTemplate": "/article/{all}",
"UpstreamHttpMethod": ["GET","POST"]
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:60003/"
}
}

  启动的时候将配置文件加进去,并且Startup中添加相应的中间件:services.AddOcelot(),app.UseOcelot();

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("ocelot.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
}).UseStartup<Startup>();

  启动三个项目,运行效果如下:

Asp.Net Core + Ocelot 网关搭建:路由简单配置

总结

  这样就能实现将网关做为统一入口,统一管理了。后续在加上各种Ocelot的功能实现。