.net core 實現 api網關 進行 api版本控制

場景html

  由一次大的項目改動引發的app端api不兼容問題,這時候就須要對api作版本控制了,權衡以後由於用戶很少,選擇了強更,沒人想在已經寫了8000行代碼的單個svc文件中維護好幾個版本的接口或者繼續新建svc(wcf配置較繁瑣),但暴露出的版本控制問題仍是要解決的,不能每次都強更呀。web

 

api版本控制方案json

  分項目進行版本控制,一個項目一個版本號,維護兩個版本號,分開部署,根據其版本號路由到對應host。api

  根據當前項目狀況,爲了同時完成技術迭代(因沒有code review,屢次經手,wcf中基於http的api已經難以維護,而且使用的是.net fx4.0,各類不便,徹底重構是不可能的),因此新版本採用restful web api(原本想直接上.net core web api,成本...)。restful

  關於api版本控制的其餘幾種方案不詳述,網上不少文章,能夠本身搜搜看,對比選用適合本身的方案。app

       rest風格的api版本控制async

此時須要將老的wcf 和新web api管理起來了,作一個api網關再合適不過 ,不只處理了版本控制的問題,後面還可擴展網關的其餘職能,邁開了從單體過渡到微服務的步伐ide

 

 

api網關方案:使用.net core web自實現(原本想使用Ocelot ,全套固然方便,因其版本控制基於url,我更傾向於rest基於http headers accept來控制,因此本身寫吧)微服務

 

api網關落地:ui

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 }
services.json

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<RequestMiddleware>();
115         }
116     }
RequestMiddleware

 目前就構建了一箇中間件,代碼寫得較亂

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<IConfiguration>(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<HttpResponseMessage>(APITimeOut);
17 
18             var retryPolicy = HttpPolicyExtensions.HandleTransientHttpError()
19             //.Or<{ExtensionsException}>()
20             .Or<TimeoutRejectedException>()
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         }
Startup

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 }
requestservices.json

 

到此,一個.net core實現的用來作api版本控制的簡單網關就搭建好了,還有不少細節須要深刻,還有不少功能須要擴展,初學.net core,歡迎指正討論!

相關文章
相關標籤/搜索