.Net Core 2.0+ InfluxDB+Grafana+App Metrics 實現跨平台的即時效能監控

來源:互聯網
上載者:User

標籤:container   influxdb   false   bsp   連接埠   螢幕   esc   1.0   資訊   

最近這段時間一直在忙,沒時間寫部落格,負責了一個項目,從前端到後端一直忙,同時還有其他第幾個項目的系統架構要處理。

去年就開始關注net core了,只是平時寫寫demo,沒用在項目中,正好這次機會就用了net core,具體是什麼時候開始的不太記得了,總之剛開始是用core 1.0開發,然後在開發的時候突然想到,平時我們的項目中都沒有做過項目的即時監控,為什麼這次不試試看呢,而且還能知道每天什麼時段的流量走向,系統輸送量等。記得之前去北京總公司的時候,看到java開發部那邊有一個大螢幕,即時的顯示項目的輸送量、請求量等資訊,感覺非常酷,我們net應該可以可以實現吧。

抱著這總心態就去找了一些相關資料,也就在項目用了起來。

項目部署在windows環境下,Influxdb的介紹這裡不再贅述。

1、首先安裝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

最後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”)

2、安裝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這一欄不需要輸入任何東西。

3、.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

 

.Net Core 2.0+ InfluxDB+Grafana+App Metrics 實現跨平台的即時效能監控

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.