场景:
由一次大的项目改动引起的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网关再合适不过 ,不仅处理了版本控制的问题,后面还可扩展网关的其他职能,迈开了从单体过渡到微服务的步伐
api网关方案:使用.net core web自实现(本来想使用Ocelot ,全套当然方便,因其版本控制基于url,我更倾向于rest基于http headers accept来控制,所以自己写吧)
api网关落地:
1.对服务的管理设计
建了一个json文件来配置对服务的管理,因其要保留网关其他职能的可能性,所以设计时要注意其扩展性,当然目前没做服务发现,所以需要这么一个设计来管理服务。
知道vnd啥意思吗?搜了半天才知道,自定义mime类型的前缀,当然在这里不是必须的,反正都是你自己约定解析的,当然对公还是遵循通用规范好一些。
rule里面是对请求的验证规则,顺便使用polly做了重试和超时。
1 { 2 "Rule": { 3 "CORS": { 4 "AllowOrigins": "", 5 "AllowMethods": "GET,POST,PUT,DELETE", 6 "AllowHeaders": "Accept,Content-Type" 7 }, 8 "Headers": { 9 "AcceptPrefix": "vnd.saas.services.", 10 "AcceptKey": "version", 11 "AcceptContentType": "json" 12 }, 13 "API": { 14 "FilterAPI": "", 15 "APITimeOut": "60" 16 } 17 18 }, 19 "Services": { 20 "main": { 21 "v1": { 22 "Host": "", 23 "Port": "", 24 "Deprecated": false 25 }, 26 "v2": { 27 "Host": "", 28 "Port": "", 29 "Deprecated": false 30 } 31 } 32 33 } 34 35 }
2.构建中间件处理请求
*注入IConfiguration和IHttpClientFactory,用来读取json配置和发送请求
*解析请求中http headers 中accept属性,我这里就是通过分割字符串来解析,反正网上我是没找到解析accept中自定义mime类型的方法,然后与配置中的要求对比,拿到其路由信息
*处理一些非法请求及错误
*发送请求到该版本服务,正确返回后响应给请求者
1 public class RequestMiddleware 2 { 3 private readonly RequestDelegate _next; 4 private readonly IConfiguration _configuration; 5 private readonly IHttpClientFactory _clientFactory; 6 7 public RequestMiddleware(RequestDelegate next, IConfiguration configuration, IHttpClientFactory clientFactory) 8 { 9 _next = next; 10 _configuration = configuration; 11 _clientFactory = clientFactory; 12 } 13 14 public async Task InvokeAsync(HttpContext context) 15 { 16 var acceptStr = context.Request.Headers["Accept"]+""; 17 var acceptPrefix= _configuration.GetSection("Rule:Headers:AcceptPrefix").Value; 18 var acceptKey = _configuration.GetSection("Rule:Headers:AcceptKey").Value; 19 var acceptContentType = _configuration.GetSection("Rule:Headers:AcceptContentType").Value; 20 var filterAPI = _configuration.GetSection("Rule:API:FilterAPI").Value; 21 var version = new ServiceVersion(); 22 var response = new HttpResponseMessage(); 23 var error_code = 0; 24 var error_message = string.Empty; 25 26 //default in now 27 var accept = new Accept() 28 { 29 ServiceName = "main", 30 Version = "v1", 31 AcceptContentType = "json" 32 }; 33 34 if (!string.IsNullOrEmpty(acceptStr)) 35 { 36 var acceptArray = acceptStr.Split(';'); 37 if (acceptArray.Length >= 2 && acceptArray[0].Contains(acceptPrefix) && acceptArray[1].Contains(acceptKey)) 38 { 39 40 accept.ServiceName = acceptArray[0].Split('+')[0].Replace(acceptPrefix, ""); 41 accept.AcceptContentType = acceptArray[0].Split('+')[1]; 42 accept.Version = acceptArray[1].Split('=')[1]; 43 } 44 45 } 46 47 if (_configuration.GetSection($"Services:{accept.ServiceName}:{accept.Version}").Exists()) 48 { 49 _configuration.GetSection($"Services:{accept.ServiceName}:{accept.Version}").Bind(version); 50 } 51 else 52 { 53 response.StatusCode= HttpStatusCode.BadRequest; 54 error_code = (int)HttpStatusCode.BadRequest; 55 error_message = "You should check that the request headers is correct"; 56 } 57 if (version.Deprecated) 58 { 59 response.StatusCode = HttpStatusCode.MovedPermanently; 60 error_code = (int)HttpStatusCode.MovedPermanently; 61 error_message = "You should check the version of the API"; 62 } 63 64 65 try 66 { 67 if (error_code == 0) 68 { 69 // filter api 70 var sourceName = context.Request.Path.Value.Split('/'); 71 if (sourceName.Length > 1 && filterAPI.Contains(sourceName[sourceName.Length - 1])) 72 accept.ServiceName = "FilterAPI"; 73 74 context.Request.Host = new HostString(version.Host, version.Port); 75 context.Request.PathBase = ""; 76 77 var client = _clientFactory.CreateClient(accept.ServiceName);//rename to filter 78 var requestMessage = context.Request.ToHttpRequestMessage(); 79 80 //var response = await Policy.NoOpAsync().ExecuteAsync(()=> { 81 // return client.SendAsync(requestMessage, context.RequestAborted); ; 82 //}); 83 response = await client.SendAsync(requestMessage, context.RequestAborted); 84 } 85 } 86 catch (Exception ex) 87 { 88 response.StatusCode= HttpStatusCode.InternalServerError; 89 error_code = (int)HttpStatusCode.InternalServerError; 90 error_message = "Internal Server Error"; 91 92 } 93 finally 94 { 95 if (error_code > 0) 96 { 97 response.Headers.Clear(); 98 response.Content = new StringContent("error is no content"); 99 response.Headers.Add("error_code", error_code.ToString()); 100 response.Headers.Add("error_message", error_message); 101 } 102 await response.ToHttpResponse(context); 103 } 104 await _next(context); 105 106 } 107 } 108 109 // Extension method used to add the middleware to the HTTP request pipeline. 110 public static class RequestMiddlewareExtensions 111 { 112 public static IApplicationBuilder UseRequestMiddleware(this IApplicationBuilder builder) 113 { 114 return builder.UseMiddleware(); 115 } 116 }
目前就构建了一个中间件,代码写得较乱
3.注册中间件和服务配置
*在ConfigureServices中将services.json注册进去,这样中间件中才能读到
*在Configure中使用中间件
1 public void ConfigureServices(IServiceCollection services) 2 { 3 4 var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("Configs/services.json").Build(); 5 services.AddSingleton(c => configuration); 6 7 var AllowOrigins =configuration.GetSection("Rule:CORS:AllowOrigins").Value.Split(','); 8 var AllowMethods = configuration.GetSection("Rule:CORS:AllowMethods").Value.Split(','); 9 var AllowHeaders = configuration.GetSection("Rule:CORS:AllowHeaders").Value.Split(','); 10 11 services.AddCors(options => options.AddPolicy( 12 "CORS", policy => policy.WithOrigins(AllowOrigins).WithHeaders(AllowHeaders).WithMethods(AllowMethods).AllowCredentials() 13 )); 14 15 var APITimeOut = int.Parse(configuration.GetSection("Rule:API:APITimeOut").Value); 16 var timeOutPolicy = Policy.TimeoutAsync (APITimeOut); 17 18 var retryPolicy = HttpPolicyExtensions.HandleTransientHttpError() 19 //.Or<{ExtensionsException}>() 20 .Or () 21 .WaitAndRetryAsync(new[] 22 { 23 TimeSpan.FromSeconds(1), 24 TimeSpan.FromSeconds(3), 25 TimeSpan.FromSeconds(6) 26 }); 27 28 var policyWrap = Policy.WrapAsync(retryPolicy,timeOutPolicy); 29 foreach (var keyValuePair in configuration.GetSection("Services").GetChildren()) //configuration..AsEnumerable() 30 { 31 //if (!keyValuePair.Key.Contains(':')) 32 services.AddHttpClient(keyValuePair.Key).AddPolicyHandler(policyWrap); //SetHandlerLifetime(TimeSpan.FromMinutes(5)); default 2 .AddPolicyHandler(timeOutPolicy) 33 } 34 } 35 36 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 37 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 38 { 39 app.UseCors("CORS"); 40 app.UseRequestMiddleware(); 41 }
4.客户端对网关的使用设计
*客户端需要自己设计如何管理它请求的服务与版本
1 { 2 "AcceptPrefix": "vnd.saas.services.", 3 "AcceptKey": "version", 4 "Main": { 5 "ServiceName": "main", 6 "LastVersion": "v1", 7 "NewestVersion": "v2", 8 "AcceptContentType": "json" 9 } 10 11 }
到此,一个.net core实现的用来做api版本控制的简单网关就搭建好了,还有很多细节需要深入,还有很多功能需要扩展,初学.net core,欢迎指正讨论!