文章目录
前言
上篇文章小试了Ocelot网关,直接对接服务进行的网关控制,在实际的生产环境中,应该是服务注入服务中心,统一的请求通过网关,网关再从服务注入中心进行获取,转发,Ocelot允许您指定服务发现提供程序,并将使用它来查找Ocelot将请求转发到的下游服务的主机和端口。目前,这仅在GlobalConfiguration部分中受支持,这意味着您为路由级别指定ServiceName的所有路由都将使用相同的服务发现提供程序。
如下图所示:
提示:以下是本篇文章正文内容,下面案例可供参考
一、使用步骤
1.安装Ocelot.Provider.Consul nuget包
代码如下(示例):
Install-Package Ocelot.Provider.Consul
2.修改Startup类,在ConfigureServices方法下添加AddConsul()
代码如下(示例):
public void ConfigureServices(IServiceCollection services)
{
services
.AddOcelot(new ConfigurationBuilder()
.AddJsonFile("Config/configuration.json", optional: false, reloadOnChange: true)
.Build())
.AddConsul()
.AddPolly();
}
3.修改Config文件夹下configuration文件配置
为了告诉Ocelot路由要将服务发现提供程序用于其主机和端口,您必须添加在向下游发出请求时希望使用的ServiceName和负载均衡器。目前,Ocelot具有可以使用的RoundRobin和LeastConnection算法。如果未指定负载均衡器,则Ocelot将不会进行负载均衡请求
上篇文章配置如下(示例):
{
"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" ]
}
]
}
修改后代码如下(示例):
{
"Routes": [
{
"DownstreamPathTemplate": "/WeatherForecast/gets",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/sss",
"UpstreamHttpMethod": [ "GET" ],
//微服务组名称
"ServiceName": "Student",
//Ocelot具有可以使用的RoundRobin和LeastConnection算法。如果未指定负载均衡器,则Ocelot将不会进行负载均衡请求
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
}
],
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Host": "127.0.0.1",
"Port": 8500,
"Type": "Consul"
}
}
}