1、NuGet安装:Ocelot
2、添加引用
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
Ocelot的主要功能是接收传入的http请求并将它们转发到下游服务。
一、Ocelot.Json配置
{
"ReRoutes": [ //ReRoutes:一个请求路由到另一个请求
{
"DownstreamPathTemplate": "/api/{everything}", //将请求转发到的URL
"DownstreamScheme": "http", //将请求转发到的URL
"DownstreamHostAndPorts": [ //将请求转发到的URL
//通常它只包含一个条目,但有时您可能希望向下游服务发送负载平衡请求,Ocelot允许您添加多个条目,然后选择一个负载平衡器。
{
"Host": "localhost",//主机
"Port": 3003//端口
},
{
"Host": "localhost",
"Port": 3004
}
],
"UpstreamPathTemplate": "/{everything}", //标识给定请求使用哪个DownstreamPathTemplate的URL
"UpstreamHttpMethod": [ "Get" ], //以便Ocelot可以区分对同一URL使用不同HTTP动词的请求
"ReRouteIsCaseSensitive": true //默认的ReRouting配置不区分大小写,为true后将区分大小写
//服务发现设置:Ocelot将从服务发现提供程序中查找下游主机和端口,并在所有可用服务中进行负载平衡请求。
"LoadBalancerOptions": { //负载均衡
"Type": "RoundRobin" //LeastConnection
}
}
],
"GlobalConfiguration": {
}
}
/* 最基本的ocelot.json
{
//处理上游请求对象
"ReRoutes": [],
//
"GlobalConfiguration": {}
}*/
二、Program配置
public static void Main(string[] args)
{
#region Ocelot
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
//配置多个特定环境文件
config
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
//AddJsonFile可配置多个配置文件
.AddJsonFile("appsettings.json", true, true)
//Ocelot需要HostingEnvironment,因此它知道要从算法中排除任何特定的环境。
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
.AddJsonFile("ocelot.json")
.AddEnvironmentVariables();
})
.ConfigureServices(s => {
//最重要!!!
s.AddOcelot();//添加ocelot服务
})
.ConfigureLogging((hostingContext, logging) => {
})
.UseIISIntegration()
.UseUrls("http://localhost:1000") //客户端访问地址
.Configure(app => {
app.UseOcelot().Wait();//设置所有ocelot中间件
})
.Build()
.Run();
#endregion
CreateHostBuilder(args).Build().Run();
}