让 Ocelot 与 asp.net core “共存”
让 Ocelot 与 asp.net core “共存”
Intro
我们的 API 之前是一个单体应用,各个模块的服务是通过 Assembly 集成在一起,最后部署在一个 web server 下的。
我们已经在拆分服务并且在 Ocelot 的基础上封装了我们自己的网关,但是服务还没有完全拆分,于是有这么一个需求,对于 Ocelot 配置的路由去交给 Ocelot 去转发到真正的服务地址,而那些 Ocelot 没有定义的路由则让交给 AspNetCore 去处理。
实现原理
实现原理是让 Ocelot 作为一个动态分支路由,只有当 Ocelot 配置了对应路由的下游地址才走 Ocelot 的分支,才把请求交给 Ocelot 处理。
我们可以使用 MapWhen 来处理,接下来就需要知道怎么样判断 Ocelot 是否配置了某一个路由,Ocelot 内部的处理管道,在向下游请求之前是要找到对应匹配的下游路由,所以我们去看一看 Ocelot 的源码,看看 Ocelot 内部是怎么找下游路由的,Ocelot 找下游路由中间件源码
public async Task Invoke(DownstreamContext context)
{
var upstreamUrlPath = context.HttpContext.Request.Path.ToString();
var upstreamQueryString = context.HttpContext.Request.QueryString.ToString();
var upstreamHost = context.HttpContext.Request.Headers["Host"];
Logger.LogDebug($"Upstream url path is {upstreamUrlPath}");
var provider = _factory.Get(context.Configuration);
// 获取下游路由
var downstreamRoute = provider.Get(upstreamUrlPath, upstreamQueryString, context.HttpContext.Request.Method, context.Configuration, upstreamHost);
if (downstreamRoute.IsError)
{
Logger.LogWarning($"{MiddlewareName} setting pipeline errors. IDownstreamRouteFinder returned {downstreamRoute.Errors.ToErrorString()}");
SetPipelineError(context, downstreamRoute.Errors);
return;
}
var downstreamPathTemplates = string.Join(", ", downstreamRoute.Data.ReRoute.DownstreamReRoute.Select(r => r.DownstreamPathTemplate.Value));
Logger.LogDebug($"downstream templates are {downstreamPathTemplates}");
context.TemplatePlaceholderNameAndValues = downstreamRoute.Data.TemplatePlaceholderNameAndValues;
await _multiplexer.Multiplex(context, downstreamRoute.Data.ReRoute, _next);
}
通过上面的源码,我们就可以判断 Ocelot 是否有与请求相匹配的下游路由信息
实现
既然找到了 Ocelot 如何找下游路由,就先给 Ocelot 加一个扩展吧,实现代码如下,Ocelot 扩展完整代码
public static IApplicationBuilder UseOcelotWhenRouteMatch(this IApplicationBuilder app,
Action<IOcelotPipelineBuilder, OcelotPipelineConfiguration> builderAction)
=> UseOcelotWhenRouteMatch(app, builderAction, new OcelotPipelineConfiguration());
public static IApplicationBuilder UseOcelotWhenRouteMatch(this IApplicationBuilder app,
Action<OcelotPipelineConfiguration> pipelineConfigurationAction,
Action<IOcelotPipelineBuilder, OcelotPipelineConfiguration> builderAction)
{
var pipelineConfiguration = new OcelotPipelineConfiguration();
pipelineConfigurationAction?.Invoke(pipelineConfiguration);
return UseOcelotWhenRouteMatch(app, builderAction, pipelineConfiguration);
}
public static IApplicationBuilder UseOcelotWhenRouteMatch(this IApplicationBuilder app, Action<IOcelotPipelineBuilder, OcelotPipelineConfiguration> builderAction, OcelotPipelineConfiguration configuration)
{
app.MapWhen(context =>
{
// 获取 OcelotConfiguration
var internalConfigurationResponse =
context.RequestServices.GetRequiredService<IInternalConfigurationRepository>().Get();
if (internalConfigurationResponse.IsError || internalConfigurationResponse.Data.ReRoutes.Count == 0)
{
// 如果没有配置路由信息,不符合分支路由的条件,直接退出
return false;
}
var internalConfiguration = internalConfigurationResponse.Data;
var downstreamRouteFinder = context.RequestServices
.GetRequiredService<IDownstreamRouteProviderFactory>()
.Get(internalConfiguration);
// 根据请求以及上面获取的Ocelot配置获取下游路由
var response = downstreamRouteFinder.Get(context.Request.Path, context.Request.QueryString.ToString(),
context.Request.Method, internalConfiguration, context.Request.Host.ToString());
// 如果有匹配路由则满足该分支路由的条件,交给 Ocelot 处理
return !response.IsError
&& !string.IsNullOrEmpty(response.Data?.ReRoute?.DownstreamReRoute?.FirstOrDefault()
?.DownstreamScheme);
}, appBuilder => appBuilder.UseOcelot(builderAction, configuration).Wait());
return app;
}
使用
在 Startup 里
ConfigurationServices 配置 mvc 和 Ocelot
Configure 方法里配置 ocelot 和 mvc
app.UseOcelotWhenRouteMatch((ocelotBuilder, pipelineConfiguration) =>
{
// This is registered to catch any global exceptions that are not handled
// It also sets the Request Id if anything is set globally
ocelotBuilder.UseExceptionHandlerMiddleware();
// This is registered first so it can catch any errors and issue an appropriate response
ocelotBuilder.UseResponderMiddleware();
ocelotBuilder.UseDownstreamRouteFinderMiddleware();
ocelotBuilder.UseDownstreamRequestInitialiser();
ocelotBuilder.UseRequestIdMiddleware();
ocelotBuilder.UseMiddleware<ClaimsToHeadersMiddleware>();
ocelotBuilder.UseLoadBalancingMiddleware();
ocelotBuilder.UseDownstreamUrlCreatorMiddleware();
ocelotBuilder.UseOutputCacheMiddleware();
ocelotBuilder.UseMiddleware<HttpRequesterMiddleware>();
// cors headers
ocelotBuilder.UseMiddleware<CorsMiddleware>();
});
app.UseMvc();
新建一个 TestController
[Route("/api/[controller]")]
public class TestController : ControllerBase
{
public IActionResult Get()
{
return Ok(new
{
Tick = DateTime.UtcNow.Ticks,
Msg = "Hello Ocelot",
});
}
}
具体代码可以参考这个 网关示例项目
示例项目的 Ocelot 配置是存在 Redis 里面的,配置的 ReRoutes 如下:
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api.php?key=free&appid=0&msg={everything}",
"UpstreamPathTemplate": "/api/chat/{everything}",
"UpstreamHttpMethod": [
"Get",
"POST",
"PUT",
"PATCH",
"DELETE",
"OPTIONS"
],
"AddHeadersToRequest": {
},
"RequestIdKey": "RequestId",
"ReRouteIsCaseSensitive": false,
"ServiceName": "",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "api.qingyunke.com",
"Port": 80
}
],
"DangerousAcceptAnyServerCertificateValidator": false
}
],
"GlobalConfiguration": {
"HttpHandlerOptions": {
"AllowAutoRedirect": false,
"UseCookieContainer": false,
"UseTracing": false
}
}
}
运行项目进行测试:
访问 Ocelot 定义的路由 http://localhost:65125/api/chat/hello ,返回信息如图所示:

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

上面正常的返回就表示我们的 Ocelot 和 Mvc 同时工作了~
Reference
- https://github.com/ThreeMammals/Ocelot
- https://github.com/WeihanLi/AspNetCorePlayground/tree/master/TestGateway
让 Ocelot 与 asp.net core “共存”的更多相关文章
- Asp.Net Core API网关Ocelot
首先,让我们简单了解下什么是API网关? API网关是一个服务器,是系统的唯一入口.从面向对象设计的角度看,它与外观模式类似.API网关封装了系统内部架构,为每个客户端提供一个定制的API.它可能还具 ...
- ASP.NET Core OceLot 微服务实践
1.OceLot中间件介绍 在传统的BS应用中,随着业务需求的快速发展变化,需求不断增长,迫切需要一种更加快速高效的软件交付方式.微服务可以弥补单体应用不足,是一种更加快速高效软件架构风格.单体应用被 ...
- (8)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- Ocelot网关(Api GateWay)
说到现在现有微服务的几点不足: 1) 对于在微服务体系中.和 Consul 通讯的微服务来讲,使用服务名即可访问.但是对于手 机.web 端等外部访问者仍然需要和 N 多服务器交互,需要记忆他们的服务 ...
- .net core 微服务架构-docker的部署-包括网关服务(Ocelot)+认证服务(IdentityServer4)+应用服务(asp.net core web api)
本文主要介绍通过Docker来部署通过.Net Core开发的微服务架构,部署的微服务主要包括统一网关(使用Ocelot开发).统一认证(IdentityServer4).应用服务(asp.net c ...
- Ocelot网关统一查看多个微服务asp.net core项目的swagger API接口
0.前言 整体架构目录:ASP.NET Core分布式项目实战-目录 一.准备 前提需要下载安装consul,项目需要懂添加swagger 统一在网关中配置多个微服务的swagger,需要用到服务注册 ...
- Asp.NET Core Nginx Ocelot ForwardedHeaders X-Forwarded-For
ocelot在部署时我使用了nginx作为转发,并配置了https证书,但是发现ocelot不支持Forward host header. https://ocelot.readthedocs.io/ ...
- ASP.NET Core on K8S学习之旅(13)Ocelot API网关接入
本篇已加入<.NET Core on K8S学习实践系列文章索引>,可以点击查看更多容器化技术相关系列文章. 上一篇介绍了Ingress的基本概念和Nginx Ingress的基本配置和使 ...
- Asp.Net Core微服务再体验
ASP.Net Core的基本配置 .在VS中调试的时候有很多修改Web应用运行端口的方法.但是在开发.调试微服务应用的时候可能需要同时在不同端口上开启多个服务器的实例,因此下面主要看看如何通过命令行 ...
- Asp.Net Core微服务初体验
ASP.Net Core的基本配置 .在VS中调试的时候有很多修改Web应用运行端口的方法.但是在开发.调试微服务应用的时候可能需要同时在不同端口上开启多个服务器的实例,因此下面主要看看如何通过命令行 ...
随机推荐
- 如何通过SQL注入获取服务器本地文件
写在前面的话 SQL注入可以称得上是最臭名昭著的安全漏洞了,而SQL注入漏洞也已经给整个网络世界造成了巨大的破坏.针对SQL漏洞,研究人员也已经开发出了多种不同的利用技术来实施攻击,包括非法访问存储在 ...
- 【转载】云计算的三种服务模式:IaaS,PaaS和SaaS
一张图就看懂了.其他的都不用说了. 原文:http://blog.csdn.net/hjxgood/article/details/18363789
- OnlineJudge测试数据生成模板
int类型数据生成一(正数最多4位): #include <bits/stdc++.h> using namespace std; int main() { freopen("t ...
- GuozhongCrawler系列教程 (5) TransactionRequest具体解释
为了实现和维护并发抓取的属性信息提供线程安全的事务请求.TransactionRequest是一个抽象类自己不能设置Processor,却须要实现 TransactionCallBack接口.Tran ...
- MVC Hidden用法
@Html.Hidden("DataSeriID",ViewBag.DataSeriID as string) 第一个参数相当于生成的ID值,后面的参数是String类型的数据,V ...
- Finally语句块的运行
一.finally语句块是否一定运行? Java中异常捕获机制try...catch...finally块中的finally语句是不是一定会被运行?非常多人都说不是.当然他们的回答是正确的,经过试验. ...
- [a,s]=[22,3]
[a,s]=[22,3] Object.assign() - JavaScript | MDN https://developer.mozilla.org/en-US/docs/Web/JavaScr ...
- 20170223 遇到自建表里面相同key值数据不唯一
我怎么发现这个表里 key值相同数据不唯一, 这两条看起来是完全相同的, 其实排序不能能合并已经说明问题.
- java 获取时间戳
//java 获取时间戳 long currentTime=System.currentTimeMillis();
- YTU 1055: 输入字符串以及输出
1055: 输入字符串以及输出 时间限制: 1 Sec 内存限制: 128 MB 提交: 694 解决: 476 题目描述 编写一函数,由实参传来一个字符串,统计此字符串中字母.数字.空格和其它字 ...