首页 > 其他分享 >NetCore Ocelot 之 请求聚合 Aggregator

NetCore Ocelot 之 请求聚合 Aggregator

时间:2023-03-04 09:46:09浏览次数:45  
标签:NetCore Aggregator Get Ocelot new var service2 service1 public

Ocelot允许声明聚合路由,把多个Routes请求batch一个对象来对客户端的请求进行响应。

1、ocelot configuration

{
      "DownstreamPathTemplate": "/api/service1",
      "DownstreamScheme": "https",
      "DownstreamHttpMethod": "Get",
      "UpstreamHttpMethod": [ "Options", "Get", "Post", "Put", "Delete" ],
      "UpstreamPathTemplate": "/Ocelot/service1",
      //"UpstreamHost": "localhost",//404 Not found
      "UseServiceDiscovery": true,
      "ServiceName": "serviceA",
      /*
      LeastConnection
      RoundRobin
      NoLoadBalance
      */
      "LoadBalancerOptions": {
        "Type": "CustomRandomLoadBalancer"
      },
      "authenticationoptions": {
        "authenticationproviderkey": "authenticationkey",
        "allowedscopes": []
      },
      "Key": "service1",
      "Priority": 11
    },
    {
      "DownstreamPathTemplate": "/api/service2",
      "DownstreamScheme": "https",
      "DownstreamHttpMethod": "Get",
      "UpstreamHttpMethod": [ "Options", "Get", "Post", "Put", "Delete" ],
      "UpstreamPathTemplate": "/Ocelot/service2",
      //"UpstreamHost": "localhost",//404 Not found
      "UseServiceDiscovery": true,
      "ServiceName": "serviceA",
      /*
      LeastConnection
      RoundRobin
      NoLoadBalance
      */
      "LoadBalancerOptions": {
        "Type": "CustomRandomLoadBalancer"
      },
      "authenticationoptions": {
        "authenticationproviderkey": "authenticationkey",
        "allowedscopes": []
      },
      "Key": "service2",
      "Priority": 12
    }
  ],
  "Aggregates": [
    {
      "RouteKeys": [
        "service1",
        "service2"
      ],
      "UpstreamPathTemplate": "/aggreate"
    }

2、创建demo NetCore API controller, service1 & service2 类似

    [Route("api/[controller]")]
    [ApiController]
    public class Service2Controller : Controller
    {
        [HttpGet]
        public IActionResult Index([FromServices] IConfiguration configuration)
        {
            var result = new
            {
                msg = $"This is service2, current date: {DateTime.Now:G}",
                ip = configuration["ip"],
                port = configuration["port"]
            };
            return new JsonResult(result);
        }
    }

3、执行结果

 

 

如何自定义聚合,在Aggregate节点添加Aggregator配置

 "Aggregates": [
    {
      "RouteKeys": [
        "service1",
        "service2"
      ],
      "UpstreamPathTemplate": "/aggreate",
      "Aggregator": "CustomAdvancedAggregator"
    }
  ]
builder.Services.AddOcelot()
    .AddSingletonDefinedAggregator<CustomAdvancedAggregator>()
    .AddCustomLoadBalancer((serviceProvider, route, serviceDiscoveryProvider) => new CustomRandomLoadBalancer(serviceDiscoveryProvider.Get))
    .AddConsul()
    .AddPolly();
 public class CustomAdvancedAggregator : IDefinedAggregator
    {
        public CustomAdvancedAggregator() { }

        public async Task<DownstreamResponse> Aggregate(List<HttpContext> responses)
        {
            var stringContent = new List<string>();
            foreach (var response in responses)
            {
                byte[] bytes = new byte[response.Response.Body.Length];
                await response.Response.Body.ReadAsync(bytes, 0, bytes.Length);
                var content = Encoding.UTF8.GetString(bytes);
                stringContent.Add(content);
            }
            var headers = responses.SelectMany(r => r.Response.Headers.Select(h => new Header(h.Key, h.Value))).Distinct().ToList();
            var downstreamResponse = new DownstreamResponse(new StringContent(String.Join(";",stringContent)), System.Net.HttpStatusCode.OK, headers, "custom aggregate");
            return downstreamResponse;
        }
    }

 

OK, 搞定!

标签:NetCore,Aggregator,Get,Ocelot,new,var,service2,service1,public
From: https://www.cnblogs.com/qindy/p/17102149.html

相关文章

  • NetCore 之 DispatchProxy
    如何使用Dispatchproxy封装RESTAPI,让API调用更简单。1、创建HttpClientDispathProxy类继承自DispatchProxypublicclassHttpClientDispathProxy<TInterface>:D......
  • NetCore JWT token
    在netcore中jwt使用场景很多,网上有很多的资料,这里不再累述,之后有机会会单独介绍,今天主要以实战为主。1、createjwttoken1publicinterfaceIJwtTokenService2......
  • NetCore Resource
    在netcore中resource的配置及应用1、创建resource资源文件   2、在容器中添加配置1builder.Services.AddLocalization(options=>options.ResourcesPath="......
  • docker下netcore内存dump
    一般开发阶段可以通过visualstudio来检查程序的内存、cup等的优化问题。vs下调试=》性能探查器,这里面大有千秋。但是好多内存问题是经过时间积累下来才暴露出来的,在生产......
  • iis7上部署netcore项目的步骤
    1、安装AspNetCoreModule托管模块(选择.NetCore3.1版本)AspNetCoreModule下载地址:https://dotnet.microsoft.com/download/dotnet-core1安装下面两个文件dotnet-sdk-3......
  • 从.net Framework4.6WPF升级到.netcore3.1/net5/6/7.0版本
    因项目需要,需将.netFramework4.6WPF升级到.netcore3.1/net5.0/6.0/7.0版本,通过很多办法解决,开始搞得一头雾水。终于,找到了办法。1、首先下载upgrade-assistant工具(.net升级......
  • .Net6 微服务之Ocelot+IdentityServer4入门看这篇就够了
    前言.Net6使用Consul实现服务注册与发现看这篇就够了.Net6使用Ocelot+Consul看这篇就够了.Net6微服务之Polly入门看这篇就够了书接上文,本文将继续建立在.N......
  • .NetCore自定义模板,发布Nuget
    1.创建模板项目框架             2.创建模板文件在项目文件夹根目录创建.template.config文件夹,在文件夹下创建新的文件:template.json  ......
  • aspnetcore 原生 DI 实现基于 key 的服务获取
    你可能想通过一个字符串或者其他的类型来获取一个具体的服务实现,那么在aspnetcore原生的MSDI中,如何实现呢?本文将介绍如何通过自定义工厂来实现。我们现在恰好有基于J......
  • aspnetcore 原生 DI 实现基于 key 的服务获取
    你可能想通过一个字符串或者其他的类型来获取一个具体的服务实现,那么在aspnetcore原生的MSDI中,如何实现呢?本文将介绍如何通过自定义工厂来实现。我们现在恰好有基于J......