本文演示一个最简单的demo,来模拟如何通过网关来访问服务,而不是直接访问服务
创建三个asp.net core web api项目,一个作为网关,两个作为服务
分别配置项目的访问路径
网关的项目使用https://localhost:5001
第一个服务的项目我这里使用
https://localhost:6001
第二个服务的项目我这里使用
https://localhost:7001
至此,服务端就已经完成了(没错,只要改个路径就好了,其他的代码全靠自动生成,因为懒得改)
OK,现在来配置网关,网关的配置也简单
先导包
Install-Package Ocelot
再修改配置文件appsetting.json为:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
//网关配置:
"Routes": [
{
//上游路径模板
"UpstreamPathTemplate": "/app1/{any}",
"UpstreamHttpMethod": [ "Get" ],
//下游路径模板
"DownstreamPathTemplate": "/{any}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 6001
}
]
},
{
"UpstreamPathTemplate": "/app2/{any}",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamPathTemplate": "/{any}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7001
}
]
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:5001" //网关地址
}
}
简单介绍一下这里的上游模板和下游模板是什么意思
其实配置网关就需要配置一组映射关系
上游模板指的是网关对应的路径
下游模板指的是映射到的服务对应的路径
比如:
“UpstreamPathTemplate”: “/app1/{any}”,
“DownstreamPathTemplate”: “/{any}”,
这就表示通过访问网关的/app1/{any}路径,实际上会映射到服务对应的/{any}路径
例如访问https://localhost:5001/app1/WeatherForecast,实际上会映射到https://localhost:6001/WeatherForecast
OK,配置文件修改好后,还需要注册一下Ocelot服务并使用它的一个中间件(常规操作)
注册服务:
services.AddOcelot(Configuration);
使用中间件(放在所有Use中间件的最后面)
app.UseOcelot().Wait();
至此,网关完成
现在启动三个项目进行测试
访问https://localhost:5001/app1/WeatherForecast访问成功(实际上访问了https://localhost:6001/WeatherForecast)
访问https://localhost:5001/app2/WeatherForecast访问成功(实际上访问了https://localhost:7001/WeatherForecast)
可以看到,通过网关访问到了服务