博客
关于我
.NET Core微服务之基于Ocelot实现API网关服务(续)
阅读量:429 次
发布时间:2019-03-06

本文共 4572 字,大约阅读时间需要 15 分钟。

Ocelot 负载均衡与请求缓存配置

为了验证负载均衡,我们配置了两个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)可选值包括:

  • RoundRobin:轮询,逐一处理。
  • LeastConnection:根据连接数分配请求。
  • NoLoadBalance:不进行负载均衡。

请求缓存

Ocelot支持对下游服务的URL进行缓存,可设置TTL(有效期)为秒。通过在路由中添加以下设置:

"FileCacheOptions": {  "TtlSeconds": 10,  "Region": "somename"}

缓存设置表示:10秒后过期。仅支持GET请求,相同URL则返回缓存结果。例如,在10秒内返回缓存结果,超过后触发负载均衡重新获取数据。

限流与熔断器

限流(RateLimit)

对请求进行限流,可防止下游服务器过载。配置示例:

"RateLimitOptions": {  "ClientWhitelist": ["admin"],  "EnableRateLimiting": true,  "Period": "1m",  "PeriodTimespan": 15,  "Limit": 5}

熔断器(QoS)

熔断功能停止转发请求,避免对故障服务和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。

集成Swagger统一API文档入口

为每个服务集成Swagger

  • 安装NuGet包:Install-Package Swashbuckle.AspNetCore
  • 修改Startup类:
  • public 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"  }}

    API网关集成Swagger

    修改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/

    你可能感兴趣的文章
    Netty源码—2.Reactor线程模型一
    查看>>
    Netty源码—4.客户端接入流程一
    查看>>
    Netty源码—4.客户端接入流程二
    查看>>
    Netty源码—5.Pipeline和Handler一
    查看>>
    Netty源码—6.ByteBuf原理二
    查看>>
    Netty源码—7.ByteBuf原理三
    查看>>
    Netty源码—7.ByteBuf原理四
    查看>>
    Netty源码—8.编解码原理二
    查看>>
    Netty源码解读
    查看>>
    Netty的Socket编程详解-搭建服务端与客户端并进行数据传输
    查看>>
    Netty相关
    查看>>
    Network Dissection:Quantifying Interpretability of Deep Visual Representations(深层视觉表征的量化解释)
    查看>>
    Network Sniffer and Connection Analyzer
    查看>>
    NetworkX系列教程(11)-graph和其他数据格式转换
    查看>>
    Networkx读取军械调查-ITN综合传输网络?/读取GML文件
    查看>>
    Net与Flex入门
    查看>>
    net包之IPConn
    查看>>
    NFinal学习笔记 02—NFinalBuild
    查看>>
    NFS共享文件系统搭建
    查看>>
    nfs复习
    查看>>