场景

  由一次大的项目改动引起的app端api不兼容问题,这时候就需要对api做版本控制了,权衡之后因为用户不多,选择了强更,没人想在已经写了8000行代码的单个svc文件中维护好几个版本的接口或者继续新建svc(wcf配置较繁琐),但暴露出的版本控制问题还是要解决的,不能每次都强更呀。

api版本控制方案

  分项目进行版本控制,一个项目一个版本号,维护两个版本号,分开部署,根据其版本号路由到对应host。

  根据当前项目情况,为了同时完成技术迭代(因没有code review,多次经手,wcf中基于http的api已经难以维护,并且使用的是.net fx4.0,各种不便,完全重构是不可能的),所以新版本采用restful web api(本来想直接上.net core web api,成本...)。

  关于api版本控制的其他几种方案不详述,网上很多文章,可以自己搜搜看,对比选用适合自己的方案。

rest风格的api版本控制

此时需要将老的wcf 和新web api管理起来了,做一个api网关再合适不过 ,不仅处理了版本控制的问题,后面还可扩展网关的其他职能,迈开了从单体过渡到SOA的步伐

api网关方案:使用.net core web自实现(本来想使用Ocelot ,全套当然方便,因其版本控制基于url,我更倾向于rest基于http headers accept来控制,所以自己写吧)

api网关落地:

1.对服务的管理设计

  建了一个json文件来配置对服务的管理,因其要保留网关其他职能的可能性,所以设计时要注意其扩展性,当然目前没做服务发现,所以需要这么一个设计来管理服务。

  知道vnd啥意思吗?搜了半天才知道,自定义mime类型的前缀,当然在这里不是必须的,反正都是你自己约定解析的,当然对公还是遵循通用规范好一些。

  rule里面是对请求的验证规则,顺便使用polly做了重试和超时。

 {
"Rule": {
"CORS": {
"AllowOrigins": "",
"AllowMethods": "GET,POST,PUT,DELETE",
"AllowHeaders": "Accept,Content-Type"
},
"Headers": {
"AcceptPrefix": "vnd.saas.services.",
"AcceptKey": "version",
"AcceptContentType": "json"
},
"API": {
"FilterAPI": "",
"APITimeOut": ""
} },
"Services": {
"main": {
"v1": {
"Host": "",
"Port": "",
"Deprecated": false
},
"v2": {
"Host": "",
"Port": "",
"Deprecated": false
}
} } }

services.json

2.构建中间件处理请求

  *注入IConfiguration和IHttpClientFactory,用来读取json配置和发送请求

  *解析请求中http headers 中accept属性,我这里就是通过分割字符串来解析,反正网上我是没找到解析accept中自定义mime类型的方法,然后与配置中的要求对比,拿到其路由信息

  *处理一些非法请求及错误

  *发送请求到该版本服务,正确返回后响应给请求者

 public class RequestMiddleware
{
private readonly RequestDelegate _next;
private readonly IConfiguration _configuration;
private readonly IHttpClientFactory _clientFactory; public RequestMiddleware(RequestDelegate next, IConfiguration configuration, IHttpClientFactory clientFactory)
{
_next = next;
_configuration = configuration;
_clientFactory = clientFactory;
} public async Task InvokeAsync(HttpContext context)
{
var acceptStr = context.Request.Headers["Accept"]+"";
var acceptPrefix= _configuration.GetSection("Rule:Headers:AcceptPrefix").Value;
var acceptKey = _configuration.GetSection("Rule:Headers:AcceptKey").Value;
var acceptContentType = _configuration.GetSection("Rule:Headers:AcceptContentType").Value;
var filterAPI = _configuration.GetSection("Rule:API:FilterAPI").Value;
var version = new ServiceVersion();
var response = new HttpResponseMessage();
var error_code = ;
var error_message = string.Empty; //default in now
var accept = new Accept()
{
ServiceName = "main",
Version = "v1",
AcceptContentType = "json"
}; if (!string.IsNullOrEmpty(acceptStr))
{
var acceptArray = acceptStr.Split(';');
if (acceptArray.Length >= && acceptArray[].Contains(acceptPrefix) && acceptArray[].Contains(acceptKey))
{ accept.ServiceName = acceptArray[].Split('+')[].Replace(acceptPrefix, "");
accept.AcceptContentType = acceptArray[].Split('+')[];
accept.Version = acceptArray[].Split('=')[];
} } if (_configuration.GetSection($"Services:{accept.ServiceName}:{accept.Version}").Exists())
{
_configuration.GetSection($"Services:{accept.ServiceName}:{accept.Version}").Bind(version);
}
else
{
response.StatusCode= HttpStatusCode.BadRequest;
error_code = (int)HttpStatusCode.BadRequest;
error_message = "You should check that the request headers is correct";
}
if (version.Deprecated)
{
response.StatusCode = HttpStatusCode.MovedPermanently;
error_code = (int)HttpStatusCode.MovedPermanently;
error_message = "You should check the version of the API";
} try
{
if (error_code == )
{
// filter api
var sourceName = context.Request.Path.Value.Split('/');
if (sourceName.Length > && filterAPI.Contains(sourceName[sourceName.Length - ]))
accept.ServiceName = "FilterAPI"; context.Request.Host = new HostString(version.Host, version.Port);
context.Request.PathBase = ""; var client = _clientFactory.CreateClient(accept.ServiceName);//rename to filter
var requestMessage = context.Request.ToHttpRequestMessage(); //var response = await Policy.NoOpAsync().ExecuteAsync(()=> {
// return client.SendAsync(requestMessage, context.RequestAborted); ;
//});
response = await client.SendAsync(requestMessage, context.RequestAborted);
}
}
catch (Exception ex)
{
response.StatusCode= HttpStatusCode.InternalServerError;
error_code = (int)HttpStatusCode.InternalServerError;
error_message = "Internal Server Error"; }
finally
{
if (error_code > )
{
response.Headers.Clear();
response.Content = new StringContent("error is no content");
response.Headers.Add("error_code", error_code.ToString());
response.Headers.Add("error_message", error_message);
}
await response.ToHttpResponse(context);
}
await _next(context); }
} // Extension method used to add the middleware to the HTTP request pipeline.
public static class RequestMiddlewareExtensions
{
public static IApplicationBuilder UseRequestMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestMiddleware>();
}
}

RequestMiddleware

目前就构建了一个中间件,代码写得较乱

3.注册中间件和服务配置

  *在ConfigureServices中将services.json注册进去,这样中间件中才能读到

  *在Configure中使用中间件

 public void ConfigureServices(IServiceCollection services)
{ var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("Configs/services.json").Build();
services.AddSingleton<IConfiguration>(c => configuration); var AllowOrigins =configuration.GetSection("Rule:CORS:AllowOrigins").Value.Split(',');
var AllowMethods = configuration.GetSection("Rule:CORS:AllowMethods").Value.Split(',');
var AllowHeaders = configuration.GetSection("Rule:CORS:AllowHeaders").Value.Split(','); services.AddCors(options => options.AddPolicy(
"CORS", policy => policy.WithOrigins(AllowOrigins).WithHeaders(AllowHeaders).WithMethods(AllowMethods).AllowCredentials()
)); var APITimeOut = int.Parse(configuration.GetSection("Rule:API:APITimeOut").Value);
var timeOutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(APITimeOut); var retryPolicy = HttpPolicyExtensions.HandleTransientHttpError()
//.Or<{ExtensionsException}>()
.Or<TimeoutRejectedException>()
.WaitAndRetryAsync(new[]
{
TimeSpan.FromSeconds(),
TimeSpan.FromSeconds(),
TimeSpan.FromSeconds()
}); var policyWrap = Policy.WrapAsync(retryPolicy,timeOutPolicy);
foreach (var keyValuePair in configuration.GetSection("Services").GetChildren()) //configuration..AsEnumerable()
{
//if (!keyValuePair.Key.Contains(':'))
services.AddHttpClient(keyValuePair.Key).AddPolicyHandler(policyWrap); //SetHandlerLifetime(TimeSpan.FromMinutes(5)); default 2 .AddPolicyHandler(timeOutPolicy)
}
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("CORS");
app.UseRequestMiddleware();
}

Startup

4.客户端对网关的使用设计

  *客户端需要自己设计如何管理它请求的服务与版本

 {
"AcceptPrefix": "vnd.saas.services.",
"AcceptKey": "version",
"Main": {
"ServiceName": "main",
"LastVersion": "v1",
"NewestVersion": "v2",
"AcceptContentType": "json"
} }

requestservices.json

到此,一个.net core实现的用来做api版本控制的简单网关就搭建好了!

.net core 实现 api网关 进行 api版本控制的更多相关文章

  1. .net core 微服务之Api网关(Api Gateway)

    原文:.net core 微服务之Api网关(Api Gateway) 微服务网关目录 1. 微服务引子 2.使用Nginx作为api网关 3.自创api网关(重复轮子) 3.1.构建初始化 3.2. ...

  2. 谈谈微服务中的 API 网关(API Gateway)

    前言 又是很久没写博客了,最近一段时间换了新工作,比较忙,所以没有抽出来太多的时间写给关注我的粉丝写一些干货了,就有人问我怎么最近没有更新博客了,在这里给大家抱歉. 那么,在本篇文章中,我们就一起来探 ...

  3. 微服务中的 API 网关(API Gateway)

    API 网关(API Gateway)提供高性能.高可用的 API 托管服务,帮助用户对外开放其部署在 ECS.容器服务等云产品上的应用,提供完整的 API 发布.管理.维护生命周期管理.用户只需进行 ...

  4. 服务中的 API 网关(API Gateway)

    我们知道在微服务架构风格中,一个大应用被拆分成为了多个小的服务系统提供出来,这些小的系统他们可以自成体系,也就是说这些小系统可以拥有自己的数据库,框架甚至语言等,这些小系统通常以提供 Rest Api ...

  5. 用API网关把API管起来

    最开始只是想找个API网关防止API被恶意请求,找了一圈发现基于Nginx的OpenResty(Lua语言)扩展模块Orange挺好(也找了Kong,但是感觉复杂了点没用),还偷懒用Vagrant结合 ...

  6. API网关在API安全性中的作用

    从单一应用程序切换到微服务时,客户端的行为不能与客户端具有该应用程序的一个入口点的行为相同.简单来说就是微服务上的某一部分功能与单独实现该应用程序时存在不同. 目前在使用微服务时,客户端必须处理微服务 ...

  7. 基于.NET CORE微服务框架 -谈谈surging API网关

    1.前言 对于最近surging更新的API 网关大家也有所关注,也收到了不少反馈提出是否能介绍下Api网关,那么我们将在此篇文章中剥析下surging的Api 网关 开源地址:https://git ...

  8. Asp.Net Core API网关Ocelot

    首先,让我们简单了解下什么是API网关? API网关是一个服务器,是系统的唯一入口.从面向对象设计的角度看,它与外观模式类似.API网关封装了系统内部架构,为每个客户端提供一个定制的API.它可能还具 ...

  9. Net Core API网关Ocelot

    Ocelot在github的地址 https://github.com/TomPallister/Ocelot , 非常给力的是在课程当天完成了.NET Core 2.0的升级,升级过程请看https ...

随机推荐

  1. 个人永久性免费-Excel催化剂插件功能修复与更新汇总篇之九

    第11波-快速批量插入图片并保护纵横比不变 原文链接:https://www.jianshu.com/p/9a3d9aa7ba7e 修复了插入图片有纵向的图片时,插入后还是显示横向的情况. 第83波- ...

  2. [POJ 2888]Magic Bracelet[Polya Burnside 置换 矩阵]

    也许更好的阅读体验 \(\mathcal{Description}\) 大意:给一条长度为\(n\)的项链,有\(m\)种颜色,另有\(k\)条限制,每条限制为不允许\(x,y\)颜色连在一起.要求有 ...

  3. RecyclerView下拉加载集合越界问题

    问题描述 在做毕业设计app中遇到这样一个问题,使用RecyclerView进行下拉加载数据的时候,比如我每次让它加载5条数据,当服务器端数据总数刚好是5的倍数的时候,不会出现下拉加载数据集合越界的问 ...

  4. python元组-字典-集合及其内置方法(下)

    列表补充 补充方法 清空列表 clear # clear 清空列表 l = [1, 2, 3, 4, 4] print(l.clear()) # clear没有返回值(None) print(l) # ...

  5. Vue的基本使用(一)

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. Go语言圣经习题练习_1.5. 获取URL

    练习 1.7: 函数调用io.Copy(dst, src)会从src中读取内容,并将读到的结果写入到dst中,使用这个函数替代掉例子中的ioutil.ReadAll来拷贝响应结构体到os.Stdout ...

  7. jsp数据交互(一).3

    引入的文件如果是jsp则应定义为***.jspf文件,如果其他文件可定义为***.inc文件,即include file. jsp:include是既可以静态包含又可以动态包含,用jsp:includ ...

  8. java.sql.SQLException: Parameter index out of range (0 < 1 ).

    向SQL中传入数据是从1开始的!!! 从ResultSet中取数据也是从1开始的!

  9. 林大妈的JavaScript基础知识(三):JavaScript编程(2)函数

    JavaScript是一门函数式的面向对象编程语言.了解函数将会是了解对象创建和操作.原型及原型方法.模块化编程等的重要基础.函数包含一组语句,它的主要功能是代码复用.隐藏信息和组合调用.我们编程就是 ...

  10. Cassandra之Docker环境实践

    Cassandra简介 Cassandra是一个开源分布式NoSQL数据库系统. 它最初由Facebook开发,用于储存收件箱等简单格式数据,集GoogleBigTable的数据模型与Amazon D ...