一、簡介
最近這段時間一直在忙,沒時間寫博客,負責了一個項目,從前端到后端一直忙,同時還有其他第幾個項目的系統架構要處理。
去年就開始關注net core了,只是平時寫寫demo,沒用在項目中,正好這次機會就用了net core,具體是什么時候開始的不太記得了,總之剛開始是用core 1.0開發,然后在開發的時候突然想到,平時我們的項目中都沒有做過項目的實時監控,為什么這次不試試看呢,而且還能知道每天什么時段的流量走向,系統吞吐量等。記得之前去北京總公司的時候,看到java開發部那邊有一個大屏幕,實時的顯示項目的吞吐量、請求量等信息,感覺非常酷,我們net應該可以可以實現吧。
抱着這總心態就去找了一些相關資料,也就在項目用了起來。
項目部署在windows環境下,Influxdb的介紹這里不再贅述。
二、安裝Influxdb
首先安裝InfluxDB時序數據庫,地址如下:https://portal.influxdata.com/downloads#influxdb ,這里我就下載Windows Binaries (64-bit),具體的寫一下配置文件和安裝過程。
解壓后打開influxdb.conf,因為influxdb的默認配置全是針對linux配置的,所以我們需要修改一下配置文件。
修改下面3個liunx的路徑,改為winodws路徑如下:
[meta] # Where the metadata/raft database is stored dir = "influxdb/meta"
[data] # The directory where the TSM storage engine stores TSM files. dir = "influxdb/data"
# The directory where the TSM storage engine stores WAL files. wal-dir = "influxdb/wal"
我將influxdb的文件都放在了influxdb目錄下,可以用相對位置,也可以用絕對位置,這個可以根據個人需要修改。
這里提一下,Influxdb v1.2.4之后好像網頁圖形化管理界面就去掉了,1.2.4之前的是有網頁圖形化管理界面的,influxdb.conf文件之前還有
[admin] # Determines whether the admin service is enabled. enabled = true # The default bind address used by the admin service. bind-address = ":8083"
不過后面的版本,conf文件里就沒有這個了,所以大家要注意一下。后面版本沒辦法用網頁圖形化管理,如果要連接Influxdb的話可以在目錄下以cmd運行influx.exe,如果不想所有人都可以訪問你的InfluxDB,那么你可以在conf文件里配置認證信息
# Determines whether HTTP endpoint is enabled.
enabled = true
# The bind address used by the HTTP service.
bind-address = ":8086"
# Determines whether user authentication is enabled over HTTP/HTTPS.
auth-enabled = true
(注意:在沒配置好賬號密碼前,請先別將上面的:auth-enabled 設置成 true,先在auth-enabled = false 不啟用身份驗證的時候,創建一個管理員權限的賬號,命令如下:CREATE USER "admin" WITH PASSWORD '123456' WITH ALL PRIVILEGES,創建好賬號后,將auth-enabled 設置成 true,然后啟動influxdb,最后使用賬號密碼的情況下創建一個名為"AppMetricsDemo"的數據,命令如下:CREATE DATABASE "AppMetricsDemo")
最后cmd運行,進入到你的解壓目錄,執行命令:
influxd -config influxdb.conf
這里說一下,使用influx.exe登錄時,輸入以下命令:influx -host 127.0.0.1 -port 8086 -username "admin" -password "123456",這樣就連上InfluxDB了。然后創建數據庫:CREATE DATABASE "AppMetricsDemo"。
如果你覺得這樣比較麻煩,可以安裝兩個influxDB,一個是V1.2.4版的,一個是最新版的,這是需要修改配置文件的端口,將兩個influxDB的端口修改成不一樣的就好,然后用1.2.4版本的連接最新版的即可,如圖,點擊右上角的齒輪圖標即可出現連接表單,
(安裝好influxDB后,記得在influxDB中創建Demo需要的數據庫“AppMetricsDemo”)
三、安裝Grafana
安裝Grafana,下載地址:https://grafana.com/get,我們解壓后進入bin目錄,如圖:
直接運行grafana-server.exe即可。
Grafana默認會監聽3000的端口,所以我們進入http://localhost:3000,
會讓你登陸,直接輸入本地的管理員帳戶即可,帳戶:admin 密碼:admin,進入后如圖:
安裝完成之后,我們下載相關儀表模版的Json文件。
地址如下:https://grafana.com/dashboards/2125
然后我們導入我們的儀表:如圖操作即可
添加我們上面的數據源,如圖:
選擇Add DataSource,然后操作如下:
這樣,我們就完成了Grafana的安裝配置和添加數據源。
由於實際項目中,我們不可能在服務器上運行個控制台去開啟這些服務,所以我們需要將influxDB和Grafana發布成服務的形式運行在服務器上,這里我們可以使用nssm工具將InfluxDB和Grafana封裝成服務運行。
下載地址如下:http://www.nssm.cc/download
解壓后進入到對應系統版本文件夾中,里面有個32位和64位的文件,根據自己的實際情況選擇,如圖:
我們選擇win64,進入文件夾后運行cmd,輸入nssm install InfluxDB 運行后出現如下界面:
重點說一下參數這一欄,Argument里輸入:-config influxdb.conf,類似上面在cmd中輸入Influxd -config influxdb.conf
安裝好后運行起來就好,Grafana的安裝類似上面的操作,只是Argument這一欄不需要輸入任何東西。
四、.netCore 中使用AppMetrics
.netCore 中使用AppMetrics,新建一個名為Demo 的api,然后編輯右鍵編輯 Demo.csproj文件,在ItemGroup節點下新增以下Package
<PackageReference Include="App.Metrics" Version="2.0.0-alpha" />
<PackageReference Include="App.Metrics.AspNetCore.Endpoints" Version="2.0.0-alpha" />
<PackageReference Include="App.Metrics.AspNetCore.Reporting" Version="2.0.0-alpha" />
<PackageReference Include="App.Metrics.AspNetCore.Tracking" Version="2.0.0-alpha" />
<PackageReference Include="App.Metrics.Extensions.Reporting.InfluxDB" Version="1.2.0" />
<PackageReference Include="App.Metrics.Formatters.Json" Version="2.0.0-alpha" />
<PackageReference Include="App.Metrics.Reporting.InfluxDB" Version="2.0.0-alpha" />
保存后,項目就引用了AppMetrics相關類庫
然后修改appsettings.json文件。添加如下代碼
{ "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } }, "InfluxDB": { "IsOpen": true, "DataBaseName": "AppMetricsDemo", "ConnectionString": "http://10.10.134.109:8086", "username": "admin", "password": "123456", "app": "RepairApp", "env": "stage" } }
ConfigureServices方法,如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using App.Metrics; namespace Demo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region Metrics監控配置 string IsOpen = Configuration.GetSection("InfluxDB")["IsOpen"].ToLower(); if (IsOpen == "true") { string database = Configuration.GetSection("InfluxDB")["DataBaseName"]; string InfluxDBConStr = Configuration.GetSection("InfluxDB")["ConnectionString"]; string app = Configuration.GetSection("InfluxDB")["app"]; string env = Configuration.GetSection("InfluxDB")["env"]; string username = Configuration.GetSection("InfluxDB")["username"]; string password = Configuration.GetSection("InfluxDB")["password"]; var uri = new Uri(InfluxDBConStr); var metrics = AppMetrics.CreateDefaultBuilder() .Configuration.Configure( options => { options.AddAppTag(app); options.AddEnvTag(env); }) .Report.ToInfluxDb( options => { options.InfluxDb.BaseUri = uri; options.InfluxDb.Database = database; options.InfluxDb.UserName = username; options.InfluxDb.Password = password; options.HttpPolicy.BackoffPeriod = TimeSpan.FromSeconds(30); options.HttpPolicy.FailuresBeforeBackoff = 5; options.HttpPolicy.Timeout = TimeSpan.FromSeconds(10); options.FlushInterval = TimeSpan.FromSeconds(5); }) .Build(); services.AddMetrics(metrics); services.AddMetricsReportScheduler(); services.AddMetricsTrackingMiddleware(); services.AddMetricsEndpoints(); } #endregion services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } #region 注入Metrics string IsOpen = Configuration.GetSection("InfluxDB")["IsOpen"].ToLower(); if (IsOpen == "true") { app.UseMetricsAllMiddleware(); // Or to cherry-pick the tracking of interest app.UseMetricsActiveRequestMiddleware(); app.UseMetricsErrorTrackingMiddleware(); app.UseMetricsPostAndPutSizeTrackingMiddleware(); app.UseMetricsRequestTrackingMiddleware(); app.UseMetricsOAuth2TrackingMiddleware(); app.UseMetricsApdexTrackingMiddleware(); app.UseMetricsAllEndpoints(); // Or to cherry-pick endpoint of interest app.UseMetricsEndpoint(); app.UseMetricsTextEndpoint(); app.UseEnvInfoEndpoint(); } #endregion app.UseMvc(); } } }
代碼這一塊基本上完成了。
五、效果
接下來運行項目,訪問以下,然后看看Grafana中的儀表盤看看
附上demo地址:https://github.com/landonzeng/AppMetricsDemo