CoreProfile 實現跨應用程式性能調整及監控
當橫跨API服務應用程式之間請求與回應效能低下,需要API服務性能調教及追蹤效能。
NuGet套件: 1 2 Install-Package CoreProfilerInstall-Package CoreProfiler.Web
環境要求:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public void Configure (IApplicationBuilder app, IWebHostEnvironment env ){ app.UseCoreProfiler(true ); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
實作內容:
方法一 : ProfilingSession.Current.WebTimingAsync 1 2 3 4 5 6 7 8 9 10 11 12 var url = this .Request.Scheme + "://" + this .Request.Host + "/home/child" ;await ProfilingSession.Current.WebTimingAsync(url, async (correlationId) =>{ using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add(CoreProfilerMiddleware.XCorrelationId, correlationId); var uri = new Uri(url); var result = await httpClient.GetStringAsync(uri); } });
方法二 : HttpClientFactory 實作 DelegatingHandler CoreProfilerDelegatingHandler.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 public class CoreProfilerDelegatingHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken ) { if (ProfilingSession.Current == null ) { return await base .SendAsync(request, cancellationToken); } string url = request.RequestUri.AbsoluteUri; var webTiming = new WebTiming ( profiler: ProfilingSession.Current.Profiler, url: url ); try { request.Headers.Add ( CoreProfilerMiddleware.XCorrelationId, webTiming.CorrelationId ); return await base .SendAsync(request, cancellationToken); } finally { webTiming.Stop(); } } }
~/Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 public class Startup { public Startup (IConfiguration configuration ) { Configuration = configuration; } public IConfiguration Configuration { get ; } public void ConfigureServices (IServiceCollection services ) { services.AddTransient<CoreProfilerDelegatingHandler>() .AddHttpClient("Tracing" ) .AddHttpMessageHandler<CoreProfilerDelegatingHandler>(); services.AddControllers(); } public void Configure (IApplicationBuilder app, IWebHostEnvironment env ) { app.UseCoreProfiler(true ); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } } }
使用HttpClientFactory已註冊過使用的name,已經註冊的HttpClient已加入CoreProfilerDelegatingHandler。
1 2 3 4 5 var httpClient = this ._httpClientFactory.CreateClient("Tracing" );var response = await httpClient.GetAsync(url).ConfigureAwait(false );
參考資料: HttpClientFactory:
CoreProfiler: