网关的作用之一,就是有统一的数据出入口,基于这个功能,我们可以在网关上配置监控,从而把所有web服务的请求应答基本数据捕获并展显出来。
关于web的监控,一般的做法是采集数据并保存,然后通过图表的方式展示出来,所使用的数据库一般是时序数据库Graphite,InfluxDB(https://portal.influxdata.com/downloads),OpenDSDB等,本文使用的是InfluxDB,展示数据一般采用一个图形化框架,本文用的是Grafana(https://grafana.com/get)
首先按上面链接下载InfluxDB和Grafana
InfluxDB下载后如下图
关于InfluxDB的操作,有相应的命令,可以参考官方文档,这里不赘述,我们只在这里创建一个数据库MetricsDB即可
Grafana下载后,在Bin目录下grafana-server.exe为启动程序,启动即可
在浏览器里输入http://localhost:3000,用户名和密码都是admin(进入后可修改)
添加DataSource
添加Dashboards,可以使用导入https://grafana.com/dashboards/2125
点击Import即可进行图形视图面板
我们使用的是App.Metrics(https://www.app-metrics.io)的包来实现监控
在OcelotGateway项目中,添加引用下面五个Nuget包
App.Metrics主包
App.Metrics.AspNetCore.Endpoints
App.Metrics.AspNetCore.Reporting
App.Metrics.AspNetCore.Tracking
App.Metrics.Reporting.InfluxDB
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.JWTAuthorizePolicy;
using App.Metrics;
using System;
namespace OcelotGateway
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
#region 注放Metrics
var metrics = AppMetrics.CreateDefaultBuilder()
.Configuration.Configure(
options =>
{
options.AddAppTag("RepairApp");
options.AddEnvTag("stage");
})
.Report.ToInfluxDb(
options =>
{
options.InfluxDb.BaseUri = new Uri("http://127.0.0.1:8086");
options.InfluxDb.Database = "AppMetricsDemo";
options.InfluxDb.UserName = "admin";
options.InfluxDb.Password = "123456";
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
#region 注放JWT
var audienceConfig = Configuration.GetSection("Audience");
//注入OcelotJwtBearer
services.AddOcelotJwtBearer(audienceConfig["Issuer"], audienceConfig["Issuer"], audienceConfig["Secret"], "GSWBearer");
#endregion
//注入配置文件,AddOcelot要求参数是IConfigurationRoot类型,所以要作个转换
services.AddOcelot(Configuration as ConfigurationRoot);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
#region Metrics中间件
app.UseMetricsAllMiddleware();
app.UseMetricsAllEndpoints();
#endregion
app.UseOcelot().Wait();
}
}
}
接下来启动AuthenticationAPI,DemoAAPI,DemoBAPI,OcelotGateway,TestClient,请求几次后,查看localhost:3000的监控页面如下:
相关文章:
原文:http://www.cnblogs.com/axzxs2001/p/8005101.html