本文共 4692 字,大约阅读时间需要 15 分钟。
为了验证负载均衡,我们配置了两个Consul Client节点,分别部署了ClientService(IP地址为192.168.80.70和192.168.80.71)。为了更直观地展示API响应来源,我们对返回值进行了调整。
[Route("api/[controller]")]public class ValuesController : Controller{ [HttpGet] public IEnumerable Get(){ return new string[] { $"ClientService: {DateTime.Now.ToString()} {Environment.MachineName}" + $"OS: {Environment.OSVersion.VersionString}" };}} 在Ocelot的配置文件中,确保启用了负载均衡设置:
{ "ReRoutes": [ { "LoadBalancerOptions": { "Type": "RoundRobin" } } ]} 发布并部署到两个节点后,启动API网关(如使用命令行启动),然后测试负载均衡效果。通过浏览器连续刷新URL,可以观察到基于轮询的负载均衡。
负载均衡类型(LoadBalance)可选值包括:
Ocelot支持对下游服务的URL进行缓存,可设置TTL(有效期)为秒。通过在路由中添加以下设置:
"FileCacheOptions": { "TtlSeconds": 10, "Region": "somename"} 缓存设置表示:10秒后过期。仅支持GET请求,相同URL则返回缓存结果。例如,在10秒内返回缓存结果,超过后触发负载均衡重新获取数据。
对请求进行限流,可防止下游服务器过载。配置示例:
"RateLimitOptions": { "ClientWhitelist": ["admin"], "EnableRateLimiting": true, "Period": "1m", "PeriodTimespan": 15, "Limit": 5} 熔断功能停止转发请求,避免对故障服务和API网关造成负担。配置示例:
"QoSOptions": { "ExceptionsAllowedBeforeBreaking": 2, "DurationOfBreak": 5000, "TimeoutValue": 3000} 通过手动设置服务延迟,测试熔断机制。异常后进入5秒不可访问状态,5秒后恢复。
Ocelot的Dynamic Routing功能减少了ReRoutes配置的复杂性。例如:
http://api.edc.com/productservice/api/products 会通过Consul服务发现获取IP和Port,构造最终URL。
Install-Package Swashbuckle.AspNetCorepublic class Startup{ public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSwaggerGen(s => { s.SwaggerDoc("Service:DocName", new Info { Title = "Service Title", Version = "1.0", Description = "Service Description", Contact = new Contact { Name = "Service Contact Name", Email = "service.contact.email" } }); var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "Service:XmlFile"); s.IncludeXmlComments(xmlPath); }); services.AddOcelot(Configuration); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); app.UseSwagger(c => { c.RouteTemplate = "doc/{documentName}/swagger.json"; }); app.UseSwaggerUI(s => { s.SwaggerEndpoint("/doc/ServiceName/swagger.json", "Service Name Version"); }); app.UseOcelot().Wait(); }} { "Service": { "Name": "CAS.NB.ClientService", "Port": "8810", "DocName": "clientservice", "Version": "v1", "Title": "CAS Client Service API", "Description": "CAS Client Service API provides client information APIs", "Contact": { "Name": "CAS 2.0 Team", "Email": "EdisonZhou@manulife.com" }, "XmlFile": "Manulife.DNC.MSAD.NB.ClientService.xml" }} 修改Startup类:
public class Startup{ public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddOcelot(Configuration); services.AddMvc(); services.AddSwaggerGen(options => { options.SwaggerDoc($"{Configuration["Swagger:DocName"]}", new Info { Title = Configuration["Swagger:Title"], Version = Configuration["Swagger:Version"] }); }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } var apiList = new List { "clientservice", "productservice", "noticeservice" }; app.UseMvc() .UseSwagger() .UseSwaggerUI(options => { apiList.ForEach(apiItem => { options.SwaggerEndpoint($"/doc/{apiItem}/swagger.json", apiItem); }); }) .UseOcelot() .Wait(); }} 通过本文,学习了Ocelot的负载均衡、缓存、限流、QoS和动态路由等功能,并通过示例验证了配置。最后通过集成Swagger实现了统一API文档入口。更多内容请访问GitHub仓库。
转载地址:http://dzduz.baihongyu.com/