让 Ocelot 与 asp.net core “共存”

Intro

我们的 API 之前是一个单体应用,各个模块的服务是通过 Assembly 集成在一起,最后部署在一个 web server 下的。

我们已经在拆分服务并且在 Ocelot 的基础上封装了我们自己的网关,但是服务还没有完全拆分,于是有这么一个需求,对于 Ocelot 配置的路由去交给 Ocelot 去转发到真正的服务地址,而那些 Ocelot 没有定义的路由则让交给 AspNetCore 去处理。

实现原理

实现原理是让 Ocelot 作为一个动态分支路由,只有当 Ocelot 配置了对应路由的下游地址才走 Ocelot 的分支,才把请求交给 Ocelot 处理。

我们可以使用 MapWhen 来处理,接下来就需要知道怎么样判断 Ocelot 是否配置了某一个路由,Ocelot 内部的处理管道,在向下游请求之前是要找到对应匹配的下游路由,所以我们去看一看 Ocelot 的源码,看看 Ocelot 内部是怎么找下游路由的,Ocelot 找下游路由中间件源码

 
 
  1. public async Task Invoke(DownstreamContext context)

  2. {

  3. var upstreamUrlPath = context.HttpContext.Request.Path.ToString();


  4. var upstreamQueryString = context.HttpContext.Request.QueryString.ToString();


  5. var upstreamHost = context.HttpContext.Request.Headers["Host"];


  6. Logger.LogDebug($"Upstream url path is {upstreamUrlPath}");


  7. var provider = _factory.Get(context.Configuration);


  8. // 获取下游路由

  9. var downstreamRoute = provider.Get(upstreamUrlPath, upstreamQueryString, context.HttpContext.Request.Method, context.Configuration, upstreamHost);


  10. if (downstreamRoute.IsError)

  11. {

  12. Logger.LogWarning($"{MiddlewareName} setting pipeline errors. IDownstreamRouteFinder returned {downstreamRoute.Errors.ToErrorString()}");


  13. SetPipelineError(context, downstreamRoute.Errors);

  14. return;

  15. }


  16. var downstreamPathTemplates = string.Join(", ", downstreamRoute.Data.ReRoute.DownstreamReRoute.Select(r => r.DownstreamPathTemplate.Value));


  17. Logger.LogDebug($"downstream templates are {downstreamPathTemplates}");


  18. context.TemplatePlaceholderNameAndValues = downstreamRoute.Data.TemplatePlaceholderNameAndValues;


  19. await _multiplexer.Multiplex(context, downstreamRoute.Data.ReRoute, _next);

  20. }

通过上面的源码,我们就可以判断 Ocelot 是否有与请求相匹配的下游路由信息

实现

既然找到了 Ocelot 如何找下游路由,就先给 Ocelot 加一个扩展吧,实现代码如下,Ocelot 扩展完整代码

 
 
  1. public static IApplicationBuilder UseOcelotWhenRouteMatch(this IApplicationBuilder app,

  2. Action<IOcelotPipelineBuilder, OcelotPipelineConfiguration> builderAction)

  3. => UseOcelotWhenRouteMatch(app, builderAction, new OcelotPipelineConfiguration());


  4. public static IApplicationBuilder UseOcelotWhenRouteMatch(this IApplicationBuilder app,

  5. Action<OcelotPipelineConfiguration> pipelineConfigurationAction,

  6. Action<IOcelotPipelineBuilder, OcelotPipelineConfiguration> builderAction)

  7. {

  8. var pipelineConfiguration = new OcelotPipelineConfiguration();

  9. pipelineConfigurationAction?.Invoke(pipelineConfiguration);

  10. return UseOcelotWhenRouteMatch(app, builderAction, pipelineConfiguration);

  11. }


  12. public static IApplicationBuilder UseOcelotWhenRouteMatch(this IApplicationBuilder app, Action<IOcelotPipelineBuilder, OcelotPipelineConfiguration> builderAction, OcelotPipelineConfiguration configuration)

  13. {

  14. app.MapWhen(context =>

  15. {

  16. // 获取 OcelotConfiguration

  17. var internalConfigurationResponse =

  18. context.RequestServices.GetRequiredService<IInternalConfigurationRepository>().Get();

  19. if (internalConfigurationResponse.IsError || internalConfigurationResponse.Data.ReRoutes.Count == 0)

  20. {

  21. // 如果没有配置路由信息,不符合分支路由的条件,直接退出

  22. return false;

  23. }


  24. var internalConfiguration = internalConfigurationResponse.Data;

  25. var downstreamRouteFinder = context.RequestServices

  26. .GetRequiredService<IDownstreamRouteProviderFactory>()

  27. .Get(internalConfiguration);

  28. // 根据请求以及上面获取的Ocelot配置获取下游路由

  29. var response = downstreamRouteFinder.Get(context.Request.Path, context.Request.QueryString.ToString(),

  30. context.Request.Method, internalConfiguration, context.Request.Host.ToString());

  31. // 如果有匹配路由则满足该分支路由的条件,交给 Ocelot 处理

  32. return !response.IsError

  33. && !string.IsNullOrEmpty(response.Data?.ReRoute?.DownstreamReRoute?.FirstOrDefault()

  34. ?.DownstreamScheme);

  35. }, appBuilder => appBuilder.UseOcelot(builderAction, configuration).Wait());


  36. return app;

  37. }

使用

在 Startup 里

ConfigurationServices 配置 mvc 和 Ocelot

Configure 方法里配置 ocelot 和 mvc

 
 
  1. app.UseOcelotWhenRouteMatch((ocelotBuilder, pipelineConfiguration) =>

  2. {

  3. // This is registered to catch any global exceptions that are not handled

  4. // It also sets the Request Id if anything is set globally

  5. ocelotBuilder.UseExceptionHandlerMiddleware();

  6. // This is registered first so it can catch any errors and issue an appropriate response

  7. ocelotBuilder.UseResponderMiddleware();

  8. ocelotBuilder.UseDownstreamRouteFinderMiddleware();

  9. ocelotBuilder.UseDownstreamRequestInitialiser();

  10. ocelotBuilder.UseRequestIdMiddleware();

  11. ocelotBuilder.UseMiddleware<ClaimsToHeadersMiddleware>();

  12. ocelotBuilder.UseLoadBalancingMiddleware();

  13. ocelotBuilder.UseDownstreamUrlCreatorMiddleware();

  14. ocelotBuilder.UseOutputCacheMiddleware();

  15. ocelotBuilder.UseMiddleware<HttpRequesterMiddleware>();

  16. // cors headers

  17. ocelotBuilder.UseMiddleware<CorsMiddleware>();

  18. });


  19. app.UseMvc();

新建一个 TestController

 
 
  1. [Route("/api/[controller]")]

  2. public class TestController : ControllerBase

  3. {

  4. public IActionResult Get()

  5. {

  6. return Ok(new

  7. {

  8. Tick = DateTime.UtcNow.Ticks,

  9. Msg = "Hello Ocelot",

  10. });

  11. }

  12. }

具体代码可以参考这个 网关示例项目

示例项目的 Ocelot 配置是存在 Redis 里面的,配置的 ReRoutes 如下:

 
 
  1. {

  2. "ReRoutes": [

  3. {

  4. "DownstreamPathTemplate": "/api.php?key=free&appid=0&msg={everything}",

  5. "UpstreamPathTemplate": "/api/chat/{everything}",

  6. "UpstreamHttpMethod": [

  7. "Get",

  8. "POST",

  9. "PUT",

  10. "PATCH",

  11. "DELETE",

  12. "OPTIONS"

  13. ],

  14. "AddHeadersToRequest": {

  15. },

  16. "RequestIdKey": "RequestId",

  17. "ReRouteIsCaseSensitive": false,

  18. "ServiceName": "",

  19. "DownstreamScheme": "http",

  20. "DownstreamHostAndPorts": [

  21. {

  22. "Host": "api.qingyunke.com",

  23. "Port": 80

  24. }

  25. ],

  26. "DangerousAcceptAnyServerCertificateValidator": false

  27. }

  28. ],

  29. "GlobalConfiguration": {

  30. "HttpHandlerOptions": {

  31. "AllowAutoRedirect": false,

  32. "UseCookieContainer": false,

  33. "UseTracing": false

  34. }

  35. }

  36. }

运行项目进行测试:

访问 Ocelot 定义的路由 http://localhost:65125/api/chat/hello ,返回信息如图所示:

640?wx_fmt=png

访问 Mvc 定义的路由 http://localhost:65125/api/test,返回信息如图所示:

640?wx_fmt=png

上面正常的返回就表示我们的 Ocelot 和 Mvc 同时工作了~

Reference

  • https://github.com/ThreeMammals/Ocelot

  • https://github.com/WeihanLi/AspNetCorePlayground/tree/master/TestGateway

640?wx_fmt=jpeg


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值