Ocelot结合Consul
引入包
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="Ocelot" Version="7.0.8" />
一.只使用Ocelot
当只使用Ocelot需要对每台服务器都进行配置,会很麻烦
{
"ReRoutes": [
{
//Ocelot转发 到本地的5001端口的地址 ...../MsgService/abc ----》 localhost:5001/api/abc
"DownstreamPathTemplate": "/api/{url}",
//请求的方式
"DownstreamScheme": "http",
//请求的主机和端口
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
//客户端请求的路由
"UpstreamPathTemplate": "/MsgService/{url}",
//允许的请求方式
"UpstreamHttpMethod": [ "Get", "Post" ]
}
]
}
二、结合Consul
结合Consul使用,不用去再一次把每台服务器配置一遍,
只需要结合Consul就能一键化配置
{
"ReRoutes": [
{
//Ocelot转发 到本地的5001端口的地址 ...../MsgService/abc ----》 localhost:5001/api/abc
"DownstreamPathTemplate": "/api/{url}",
//请求的方式
"DownstreamScheme": "http",
//请求的服务名
"ServiceName": "MsgService",
"LoadBalancerOptions": {
//对于被发现服务器的使用方式
"Type": "RoundRobin"
},
//开启服务发现
"UseServiceDiscovery": true,
//客户端请求的路由
"UpstreamPathTemplate": "/MsgService/{url}",
//允许的请求方式
"UpstreamHttpMethod": [ "Get", "Post" ]
},
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"ServiceName": "ProductService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
},
"UseServiceDiscovery": true,
"UpstreamPathTemplate": "/ProductService/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ]
}
],
//全局配置Consul服务器
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500
}
}
}
本文介绍了如何使用Ocelot作为API网关,并结合Consul进行服务发现和负载均衡。通过引入Consul,可以避免在每台服务器上手动配置,实现一键化配置,简化了微服务架构中的路由管理。配置示例展示了如何配置ReRoutes,以及如何在GlobalConfiguration中设置Consul服务发现提供者。
444

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



