ASP.NET Core WebAPI中的分析工具MiniProfiler


介紹

作為一個開發人員,你知道如何分析自己開發的Api性能么?

在Visual Studio和Azure中, 我們可以使用Application Insight來監控項目。除此之外我們還可以使用一個免費工具Stackify Prefix,它允許追蹤所有的Http請求, 這里有一篇博客講解了如何使用Stackify Prefix(Scalable and Performant ASP.NET Core Web APIs: Profiling and Monitoring)。

本文我將引入另外一個工具MiniProfiler, 我將講解如何將MiniProfiler集成到ASP.NET Core WebAPI中。

Stackify Prefix相似,MiniProfiler也是一款免費的工具(官網地址:https://miniprofiler.com/dotnet/),你可以使用它精確的分析ASP.NET和ASP.NET Core應用程序的任何代碼。

Tips: MiniProfiler在ASP.NET和控制台程序中也可以使用哦。

安裝

我們可以使用Nuget來下載這個包。

PM> Install-Package MiniProfiler.AspNetCore.Mvc

配置Startup.cs

MiniProfiler配置起來很簡單,只需要以下幾步

ConfigureServices方法中添加MiniProfiler服務

public void ConfigureServices(IServiceCollection services)
{
   services.AddMiniProfiler(options =>
      options.RouteBasePath = "/profiler"
   );
}
  • 這里是配置了MiniProfiler的路由基礎路徑,默認的路徑是/mini-profiler-resources
  • 按照當前配置,你可以使用"/profiler/results"來訪問分析報告

激活中間件,啟用MiniProfiler服務

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
   app.UseMiniProfiler();
}

配置需要監控分析的代碼

public class ValueController : ControllerBase
{
   [HttpGet]
   public IEnumerable<string> Get()
   {
      string url1 = string.Empty;
      string url2 = string.Empty;
      using (MiniProfiler.Current.Step("Get方法"))
      {
         using (MiniProfiler.Current.Step("准備數據"))
         {
            using (MiniProfiler.Current.CustomTiming("SQL", "SELECT * FROM Config"))
            {
               // 模擬一個SQL查詢
               Thread.Sleep(500);
               
               url1 = "https://www.baidu.com";
         	   url2 = "https://www.sina.com.cn/";
            }
         }
         
         
         using (MiniProfiler.Current.Step("使用從數據庫中查詢的數據,進行Http請求"))
         {
            using (MiniProfiler.Current.CustomTiming("HTTP", "GET " + url1))
            {
               var client = new WebClient();
               var reply = client.DownloadString(url1);
            }

            using (MiniProfiler.Current.CustomTiming("HTTP", "GET " + url2))
            {
               var client = new WebClient();
               var reply = client.DownloadString(url2);
            }
         }
      }
      return new string[] { "value1", "value2" }; 
   }
}

代碼解釋:

  • MiniProfiler.Current.Step方法定義了分析的步驟,這個方法可以接受一個String類型的參數,它會顯示在最終的報告中
  • MiniProfiler.Current.CustomTiming方法是更細粒度的對報告內容進行分類,以上代碼中定義了2種分類,一種是SQL, 一種是Http
  • 上述程序的功能: 模擬從數據庫拉取2個網站的Url, 並使用WebClient來分別請求網站的Url

查看效果

下面我們啟動項目, 項目默認打開/api/values

然后我們來訪問以下/profiler/results, 就會出現如下頁面

如上圖所示,我們可以很清楚的看到代碼中每一部分的耗時,由於我們添加了2種分類SQL和Http,所以列表中會對2種分類進行匯總。

重點: 當前頁面只會顯示最近的一次請求

從當前報告中可以得到以下結論

  • 當前請求總響應時間 1723.6ms
  • SQL語句查詢耗時517.ms
  • 2次Http請求共耗時868.3ms, 其中訪問百度耗時424.6ms, 訪問新浪耗時443.7ms

如何讓MiniProfiler與Swagger集成

這里我們就不再講如何在ASP.NET Core中整合Swagger。

MiniProfiler和Swagger是可以集成在一起的,為了完成這個功能,我們需要進行以下幾步

下載Swagger自定義頁面

默認的index.html頁面可以從如下鏈接下載

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.SwaggerUI/index.html

下載之后將這個文件放置到項目根目錄下。

接下來我們需要在這個文件的頭部加入如下腳本代碼:

<script async="async" id="mini-profiler" src="/profiler/includes.min.js?v=4.0.138+gcc91adf599" 
        data-version="4.0.138+gcc91adf599" data-path="/profiler/" 
        data-current-id="4ec7c742-49d4-4eaf-8281-3c1e0efa748a" data-ids="" data-position="Left" 
        data-authorized="true" data-max-traces="15" data-toggle-shortcut="Alt+P" 
        data-trivial-milliseconds="2.0" data-ignored-duplicate-execute-types="Open,OpenAsync,Close,CloseAsync">
</script>

最后我們需要配置這個index.html文件的Bulid Action為Embedded resource

安裝自定義頁面

Startup.cs文件中,我們需要修改UseSwaggerUI中間件的配置,這里我們需要添加一個InputStream配置。

app.UseSwaggerUI(c =>
{
   c.RoutePrefix = "swagger";
   c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
   c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("MiniProfilerSample.index.html");
});

注意:這里MiniProfilerSample是項目的命名空間名

最終效果

重新啟動項目,Swagger文檔頁面的左上角就出現了一個小的面板,當模擬請求一個連接之后,它就會顯示出當前請求的分析數據,看起來是不是很酷炫。

總結

本篇博客描述了如何使用MiniProfiler來監控分析你的Api。 MiniProfiler除了提供網頁顯示報告,還支持將報告結果存儲在數據庫中,后面我會補充一篇文章來說明如何將報告保存到數據庫中。

本篇源代碼: https://github.com/lamondlu/Sample_MiniProfiler


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM