一:环境配置
依赖项目:.Net Core 2.0 空项目
下载NuGet包:Install-Package Ocelot
二:相关代码与其他配置
添加应用设置文件:Ocelot.json
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8081
}
],
"UpstreamPathTemplate": "/Test/{url}",
//负载均衡
"LoadBalancer": "LeastConnection", //将请求发往最空闲的那个服务器 RoundRobin(轮流发送)、NoLoadBalance(总是发往第一个请求或者是服务发现)
"UpstreamHttpMethod": [ "Get", "Post", "Delete" ],
//限流
"RateLimitOptions": {
"ClientWhitelist": [], //白名单
"EnableRateLimiting": true, //是否启用限流
"Period": "1s", //统计时间段 1s, 5m, 1h, 1d
"PeriodTimespan": 1, //多少秒之后客户端可以重试
"Limit": 1 //在统计时间段内允许的最大请求数量
},
//服务质量与熔断
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3, //允许多少个异常请求
"DurationOfBreak": 5, //熔断的时间,单位为秒
"TimeoutValue": 5000 //如果下游请求的处理时间超过多少则自如将请求设置为超时
}
//"AuthenticationOptions": {
// "AuthenticationProviderKey": "OcelotKey",
// "AllowedScopes": []
//}
},
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8082
}
],
"UpstreamPathTemplate": "/Test2/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ]
}
]
}
将配置文件加入ASP.NET Core Configuration
Program.cs:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
配置依赖注入与中间件
Startup.cs文件中:
引用:
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
添加:
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("Ocelot.json", false, true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseOcelot().Wait();
//app.Run(async (context) =>
//{
// await context.Response.WriteAsync("Hello World!");
//});
}
}
搭建完成~
备注:Ocelot.json配置中localhost:8081,localhost:8082为测试webApi项目
测试:(网关项目)localhost:8083/Test/api/Values
Ocelot网关详细教程参考文章:https://www.cnblogs.com/jesse2013/p/net-core-apigateway-ocelot-docs.html