数据库监控
Micrometer 可以检测与数据库交互的各种库:
数据源观测仪表化
通过 Datasource Micrometer 项目,你可以对你的 DataSource
进行监控,使其在与数据库交互时开始生成 Observations。这意味着根据你的 Observation Handler 设置,你可以插入生成指标或分布式追踪的功能。
你可以在这里阅读更多关于 Datasource Micrometer 的参考文档。
数据源指标检测
// Binding instrumentation through static method
DatabaseTableMetrics.monitor(registry, "foo", "mydb", ds);
// Usage example
try (Connection conn = ds.getConnection()) {
conn.prepareStatement("CREATE TABLE foo (id int)").execute();
conn.prepareStatement("INSERT INTO foo VALUES (1)").executeUpdate();
}
assertThat(registry.get("db.table.size").tag("table", "foo").tag("db", "mydb").gauge().value()).isEqualTo(1.0);
jOOQ 工具化
// Setting up instrumentation
Configuration configuration = new DefaultConfiguration().set(conn).set(SQLDialect.H2);
MetricsDSLContext jooq = MetricsDSLContext.withMetrics(DSL.using(configuration), meterRegistry, Tags.empty());
// Usage example
jooq.tag("name", "selectAllAuthors").execute("SELECT * FROM author");
assertThat(meterRegistry.get("jooq.query").tag("name", "selectAllAuthors").timer().count()).isEqualTo(1);
PostgreSQL 监控
// Setting up instrumentation
new PostgreSQLDatabaseMetrics(dataSource, postgres.getDatabaseName()).bindTo(registry);
// Usage example
executeSql("CREATE TABLE gauge_test_table (val varchar(255))",
"INSERT INTO gauge_test_table (val) VALUES ('foo')", "UPDATE gauge_test_table SET val = 'bar'",
"SELECT * FROM gauge_test_table", "DELETE FROM gauge_test_table");
Thread.sleep(PGSTAT_STAT_INTERVAL);
final List<String> GAUGES = Arrays.asList(SIZE, CONNECTIONS, ROWS_DEAD, LOCKS);
for (String name : GAUGES) {
assertThat(get(name).gauge().value()).withFailMessage("Gauge " + name + " is zero.").isGreaterThan(0);
}