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

    你可能感兴趣的文章
    NTP及Chrony时间同步服务设置
    查看>>
    NTP服务器
    查看>>
    NTP配置
    查看>>
    NUC1077 Humble Numbers【数学计算+打表】
    查看>>
    NuGet Gallery 开源项目快速入门指南
    查看>>
    NuGet(微软.NET开发平台的软件包管理工具)在VisualStudio中的安装的使用
    查看>>
    nuget.org 无法加载源 https://api.nuget.org/v3/index.json 的服务索引
    查看>>
    Nuget~管理自己的包包
    查看>>
    NuGet学习笔记001---了解使用NuGet给net快速获取引用
    查看>>
    nullnullHuge Pages
    查看>>
    NullPointerException Cannot invoke setSkipOutputConversion(boolean) because functionToInvoke is null
    查看>>
    null可以转换成任意非基本类型(int/short/long/float/boolean/byte/double/char以外)
    查看>>
    Numix Core 开源项目教程
    查看>>
    numpy
    查看>>
    NumPy 库详细介绍-ChatGPT4o作答
    查看>>
    NumPy 或 Pandas:将数组类型保持为整数,同时具有 NaN 值
    查看>>
    numpy 或 scipy 有哪些可能的计算可以返回 NaN?
    查看>>
    numpy 数组 dtype 在 Windows 10 64 位机器中默认为 int32
    查看>>
    numpy 数组与矩阵的乘法理解
    查看>>
    NumPy 数组拼接方法-ChatGPT4o作答
    查看>>