初探基于Asp.Net Core 3.1的Ocelot网关
环境Asp.Net Core 3.1
一:搭建ApiGateway
1:新建一个NetCore项目
引入Ocelot包
Install-Package Ocelot
2:添加Ocelot的配置文件,我命名为Config.json
Ocelot的配置文件一定要根据NetCore的版本来配置,netCore1.0 、2.0、3.0+都有一些不同,建议参考官网配置
{
"Routes": [
{
"DownstreamPathTemplate": "/{url}",
"UpstreamPathTemplate": "/{url}",
"UpstreamHttpMethod": [
"Get"
],
"DownstreamHttpMethod": "Get",
"DownstreamHttpVersion": "",
"AddHeadersToRequest": {},
"AddClaimsToRequest": {},
// 授权 身份验证
"RouteClaimsRequirement": {
// "UserType":"registered"
},
"AddQueriesToRequest": {},
"RequestIdKey": "",
"FileCacheOptions": {
"TtlSeconds": 0,
"Region": ""
},
"RouteIsCaseSensitive": false,
"ServiceName": "",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8081
},
{
"Host": "localhost",
"Port": 8082
}
],
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 0,
"DurationOfBreak": 0,
"TimeoutValue": 0
},
//负载均衡算法
// LeastConnection:请求最空闲的服务器
// RoundRobin:轮流
// NoLoadBalance:总是发往第一个请求或者是服务发现
"LoadBalancerOptions": {
"Type": "LeastConnection"
},
"RateLimitOptions": {
"ClientWhitelist": [],
"EnableRateLimiting": false,
"Period": "",
"PeriodTimespan": 0,
"Limit": 0
},
"AuthenticationOptions": {
"AuthenticationProviderKey": "",
"AllowedScopes": []
},
"HttpHandlerOptions": {
"AllowAutoRedirect": true,
"UseCookieContainer": true,
"UseTracing": true,
"MaxConnectionsPerServer": 100
},
"DangerousAcceptAnyServerCertificateValidator": false
}
],
"GlobalConfiguration": {
//外部暴露的Url
"BaseUrl": "http://localhost:8080",
//限流扩展配置
"RateLimitOptions": {
//Http头 X-Rate-Limit 和 Retry-After 是否禁用
"DisableRateLimitHeaders": false,
//当请求过载被截断时返回的消息
"QuotaExceededMessage": "请求超出最大限制!",
//当请求过载被截断时返回的http status
"HttpStatusCode": 999,
//用来识别客户端的请求头,默认是 ClientId
"ClientIdHeader": "ClientId"
}
}
}
3:配置Program
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureAppConfiguration((hostingContext,config)=> {
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("Config.json", true, true)
.AddEnvironmentVariables();
});
4: 配置Startup
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// 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, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseOcelot().Wait();
}
}
5:创建两个webApi项目
Service001: 将端口设置为8081
[Route("/[controller]")]
[ApiController]
public class HomeController : ControllerBase
{
[HttpGet]
public string GetUser()
{
return string.Format("Service001 {0}", DateTime.Now);
}
}
Service002:将端口设置为8082
[Route("/[controller]")]
[ApiController]
public class HomeController : ControllerBase
{
[HttpGet]
public string GetUser()
{
return string.Format("Service002 {0}", DateTime.Now);
}
}
运行看结果:



浙公网安备 33010602011771号