SpringBoot+HikariCP+Dropwizard-Metrics统计连接池使用情况
SpringBoot+HikariCP+Dropwizard-Metrics统计连接池使用情况
背景,HikariCP是Java目前使用最广的连接池工具类,SpringBoot默认也是用这个,现在想获取连接池使用情况。
这里假设SpringBoot已集成HikariCP
1.pom.xml加上Dropwizard-Metrics配置
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-healthchecks</artifactId>
</dependency>
2在应用启动的时候连接池注册统计接口
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class ApplicationRunner implements ApplicationRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationRunner.class);
@Autowired
private DataSource dataSource;
@Override
public void run(ApplicationArguments args) throws Exception {
try {
// see detail https://github.com/brettwooldridge/HikariCP/wiki/Dropwizard-Metrics
// 连接池注册统计接口
MetricRegistry metricRegistry = new MetricRegistry();
if(dataSource instanceof HikariDataSource) {
((HikariDataSource) dataSource).setMetricRegistry(metricRegistry);
}
// 定时打印连接池使用情况
Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry).build();
reporter.start(1, TimeUnit.MINUTES);
} catch (Exception e) {
String msg = "服务启动异常";
LOGGER.error(msg, e);
throw new IllegalStateException(msg, e);
}
}
}
3 提供http请求获取连接池使用情况
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* 远程使用的RestTemplatebean,与服务间调用区分开来
*/
@Configuration
public class RestTemplateConfig {
@Bean("remoteRestTemplate")
public RestTemplate remoteRestTemplate() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(180000);
factory.setConnectTimeout(8000);
return new RestTemplate(factory);
}
}
import com.codahale.metrics.*;
import com.netflix.appinfo.InstanceInfo;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
@RestController
@RequestMapping("hikariCpStatsController")
public class HikariCpStatsController {
private static final String SERVICE_NAME ="xiaoniu";
@Autowired
private DataSource dataSource;
@Autowired
private DiscoveryClient discoveryClient;
@Qualifier("remoteRestTemplate")
@Autowired
private RestTemplate restTemplate;
@GetMapping("poolStatsHa")
public TreeMap<String, Object> poolStatsHa() {
MetricRegistry metricRegistry = null;
if (dataSource instanceof HikariDataSource) {
metricRegistry = (MetricRegistry) ((HikariDataSource) dataSource).getMetricRegistry();
}
if (metricRegistry == null)
return null;
TreeMap<String, Object> dataAll = new TreeMap<>();
// 节点的信息
List<ServiceInstance> instances = discoveryClient.getInstances(SERVICE_NAME);
for (ServiceInstance instance : instances) {
InstanceInfo instanceInfo = ((EurekaDiscoveryClient.EurekaServiceInstance) instance).getInstanceInfo();
TreeMap data = restTemplate.getForObject(instance.getUri().toString() + "/hikariCpStatsController/poolStats", TreeMap.class);
dataAll.put(instanceInfo.getInstanceId(), data);
}
return dataAll;
}
@GetMapping("poolStats")
public TreeMap<String, Object> poolStats() {
MetricRegistry metricRegistry = null;
if (dataSource instanceof HikariDataSource) {
metricRegistry = (MetricRegistry) ((HikariDataSource) dataSource).getMetricRegistry();
}
if (metricRegistry == null)
return null;
TreeMap<String, Object> data = new TreeMap<>();
SortedMap<String, Gauge> gauges = metricRegistry.getGauges();
for (Map.Entry<String, Gauge> gaugeEntry : gauges.entrySet()) {
String key = gaugeEntry.getKey();
Gauge value = gaugeEntry.getValue();
data.put(key, value.getValue());
}
SortedMap<String, Timer> timers = metricRegistry.getTimers();
for (Map.Entry<String, Timer> timerEntry : timers.entrySet()) {
String key = timerEntry.getKey();
Timer value = timerEntry.getValue();
data.put(key, "获取连接时99%线程等待的纳秒=" + value.getSnapshot().get99thPercentile());
}
SortedMap<String, Meter> meters = metricRegistry.getMeters();
for (Map.Entry<String, Meter> meterEntry : meters.entrySet()) {
String key = meterEntry.getKey();
Meter value = meterEntry.getValue();
data.put(key, "count=" + value.getCount());
}
SortedMap<String, Histogram> histograms = metricRegistry.getHistograms();
for (Map.Entry<String, Histogram> histogramEntry : histograms.entrySet()) {
String key = histogramEntry.getKey();
Histogram value = histogramEntry.getValue();
data.put(key, "99%连接线程使用的毫秒=" + value.getSnapshot().get99thPercentile());
}
return data;
}
}
在此大功告成
参考// see detail https://github.com/brettwooldridge/HikariCP/wiki/Dropwizard-Metrics
SpringBoot+HikariCP+Dropwizard-Metrics统计连接池使用情况的更多相关文章
- SpringBoot 整合mongoDB并自定义连接池
SpringBoot 整合mongoDB并自定义连接池 得力于SpringBoot的特性,整合mongoDB是很容易的,我们整合mongoDB的目的就是想用它给我们提供的mongoTemplate,它 ...
- (二)SpringBoot整合常用框架Druid连接池
一,在Pom.xml文件加入依赖 找到<dependencies></dependencies>标签,在标签中添加Druid依赖 <dependency> < ...
- 基于HiKariCP组件,分析连接池原理
HiKariCP作为SpringBoot2框架的默认连接池,号称是跑的最快的连接池,数据库连接池与之前两篇提到的线程池和对象池,从设计的原理上都是基于池化思想,只是在实现方式上有各自的特点:
- SpringBoot整合自定义FTP文件连接池
说明:通过GenericObjectPool实现的FTP连接池,记录一下以供以后使用环境:JDK版本1.8框架 :springboot2.1文件服务器: Serv-U1.引入依赖 <!--ftp ...
- SQL server 数据连接池使用情况检测
1.依据HOST_NAME请求session_id 查询 select DB_NAME(database_id) dbname,login_name,t1.session_id,t1.request_ ...
- SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件
原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...
- Java代码生成器加入postgresql数据库、HikariCP连接池、swagger2支持!
目录 前言 PostgreSql VS MySql HikariCP VS Druid Swagger2 自定义参数配置一览 结语 前言 最近几天又抽时间给代码生成器增加了几个新功能(预计今晚发布 ...
- Spring系列之HikariCP连接池
上两篇文章,我们讲到了Spring中如何配置单数据源和多数据源,配置数据源的时候,连接池有很多选择,在SpringBoot 1.0中使用的是Tomcat的DataSource,在SpringBoot ...
- SpringBoot系列之Hikari连接池
1.springboot 2.0 中默认连接池是Hikari,在引用parents后不用专门再添加依赖 2.application.yml中的配置 # jdbc_config datasource s ...
随机推荐
- Redis学习(一)认识并安装redis
一.初识redis Redis是一个开源的Key-Value数据库,通常被称为数据结构服务器,其值可以是多种常见的数据格式,且读写性能极高,且所有操作都是原子性的. Redis是运行在内存中的,但是可 ...
- nginx安装步骤
1.下载地址:下载nginx压缩包wget -c https://nginx.org/download/nginx-1.10.1.tar.gz2.配置nginx安装所需的环境yum install g ...
- 在Ubuntu下部署Flask项目
FlaskDemo 命名为test.py # coding=utf-8 from flask import Flask app = Flask(__name__) @app.route("/ ...
- Django在Linux上uwsgi 与nginx的问题与解决
1.出现只有weclome to nginx 多半是是nginx的配置文件没有修改,把他的路由注释掉. 我是修改错文件夹了,一直在自己下载而非运行的文件夹修改 2.出现502 出现了多次502这里一一 ...
- java基础篇1
JAVA基础篇1 注释 单行注释 //这是一个单行注释,由两个斜杠组成,不能嵌套多行注释 多行注释 /*这是一个 多行注释 ,//里面不能嵌套多行注释, 但是可以嵌套单行注释*/ 文档注释 /**ja ...
- 【记】《.net之美》之读书笔记(一) C#语言基础
前言 工作之中,我们习惯了碰到任务就直接去实现其业务逻辑,但是C#真正的一些基础知识,在我们久而久之不去了解巩固的情况下,就会忽视掉.我深知自己正一步步走向只知用法却不知原理的深渊,所以工作之余,一直 ...
- Centos-当前和过去登入系统用户信息-last
last 获取当前和过去登入系统的用户相关信息,执行last指令的时候会默认读取/var/log/wtmp文件 相关参数 -a 把客户端IP显示到最后一列 -R 不显示客户端IP地址或主机名 -n 显 ...
- TCP/IP 邮件
原文:TCP/IP 邮件 第一节:TCP/IP 简介 第二节:TCP/IP 寻址 第三节:TCP/IP 协议 第四节:TCP/IP 邮件 电子邮件是 TCP/IP 最重要的应用之一. 你不会用到... ...
- 题解 P3572 [POI2014]PTA-Little Bird
P3572 [POI2014]PTA-Little Bird 首先,这道题的暴力dp非常好写 就是枚举所有能转移到他的点,如果当前枚举到的位置的值大于 当前位置的话,\(f[i]=min(f[i],f ...
- Black-Lives-Matter-Resources
下载 Black-Lives-Matter-ResourcesBlack-Lives-Matter-Resources 关于最近在美国发生的事件的资源列表 链接 描述 由于(可选) 插入链接 在这里插 ...