博客
关于我
.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/

    你可能感兴趣的文章
    pandas某一列转数组list
    查看>>
    Pandas模块,我觉得掌握这些就够用了!
    查看>>
    Pandas玩转文本处理!
    查看>>
    pandas的to_sql方法中使用if_exists=‘replace‘
    查看>>
    pandas读取parquet报错
    查看>>
    spring5-介绍Spring框架
    查看>>
    PandoraFMS 监控软件 任意文件上传漏洞复现
    查看>>
    Parallel.ForEach的基础使用
    查看>>
    parallels desktop for mac安装虚拟机 之parallelsdesktop密钥 以及 parallels desktop安装win10的办公推荐可以提高办公效率...
    查看>>
    ParseChat应用源码ios版
    查看>>
    Part 2异常和错误
    查看>>
    PAT 1027 Colors in Mars
    查看>>
    PAT 1127 ZigZagging on a Tree[难]
    查看>>
    PAT 2-07. 素因子分解(20)
    查看>>
    PAT-乙级-1040 有几个PAT
    查看>>
    PATA1038题解(需复习)
    查看>>
    Patching Array
    查看>>
    Path does not chain with any of the trust anchors
    查看>>
    Path形状获取字符串型变量数据
    查看>>
    PAT甲级——1001 A+B Format (20分)
    查看>>