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统计连接池使用情况的更多相关文章

  1. SpringBoot 整合mongoDB并自定义连接池

    SpringBoot 整合mongoDB并自定义连接池 得力于SpringBoot的特性,整合mongoDB是很容易的,我们整合mongoDB的目的就是想用它给我们提供的mongoTemplate,它 ...

  2. (二)SpringBoot整合常用框架Druid连接池

    一,在Pom.xml文件加入依赖 找到<dependencies></dependencies>标签,在标签中添加Druid依赖 <dependency> < ...

  3. 基于HiKariCP组件,分析连接池原理

    HiKariCP作为SpringBoot2框架的默认连接池,号称是跑的最快的连接池,数据库连接池与之前两篇提到的线程池和对象池,从设计的原理上都是基于池化思想,只是在实现方式上有各自的特点:

  4. SpringBoot整合自定义FTP文件连接池

    说明:通过GenericObjectPool实现的FTP连接池,记录一下以供以后使用环境:JDK版本1.8框架 :springboot2.1文件服务器: Serv-U1.引入依赖 <!--ftp ...

  5. SQL server 数据连接池使用情况检测

    1.依据HOST_NAME请求session_id 查询 select DB_NAME(database_id) dbname,login_name,t1.session_id,t1.request_ ...

  6. SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件

    原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...

  7. Java代码生成器加入postgresql数据库、HikariCP连接池、swagger2支持!

    目录 前言 PostgreSql VS MySql HikariCP VS Druid Swagger2 自定义参数配置一览 结语 前言   最近几天又抽时间给代码生成器增加了几个新功能(预计今晚发布 ...

  8. Spring系列之HikariCP连接池

    上两篇文章,我们讲到了Spring中如何配置单数据源和多数据源,配置数据源的时候,连接池有很多选择,在SpringBoot 1.0中使用的是Tomcat的DataSource,在SpringBoot ...

  9. SpringBoot系列之Hikari连接池

    1.springboot 2.0 中默认连接池是Hikari,在引用parents后不用专门再添加依赖 2.application.yml中的配置 # jdbc_config datasource s ...

随机推荐

  1. python中闭包详解

    谈谈自己的理解:python中闭包,闭包的实质   闭包这个概念好难理解,身边朋友们好多都稀里糊涂的,稀里糊涂的林老冷希望写下这篇文章能够对稀里糊涂的伙伴们有一些帮助~ 请大家跟我理解一下,如果在一个 ...

  2. Spring Boot 自动配置的原理、核心注解以及利用自动配置实现了自定义 Starter 组件

    本章内容 自定义属性快速入门 外化配置 自动配置 自定义创建 Starter 组件 摘录:读书是读完这些文字还要好好用心去想想,写书也一样,做任何事也一样 图 2 第二章目录结构图 第 2 章 Spr ...

  3. Centos-删除文件或目录-rm

    rm 删除目录或者文件,如果是链接文件,则只删除这个链接文件而不是链接指向的文件 相关选项 -r 递归删除目录 -f 忽略不存在提示和确认提示,本身确认提示系统默认添加-i参数 -i 删除文件前提示, ...

  4. Python练习题 017:三支乒乓球队出赛名单

    [Python练习题 017] 两个乒乓球队进行比赛,各出三人.甲队为a,b,c三人,乙队为x,y,z三人.已抽签决定比赛名单.有人向队员打听比赛的名单.a说他不和x比,c说他不和x,z比.请编程序找 ...

  5. 080 01 Android 零基础入门 02 Java面向对象 01 Java面向对象基础 01 初识面向对象 05 单一职责原则

    080 01 Android 零基础入门 02 Java面向对象 01 Java面向对象基础 01 初识面向对象 05 单一职责原则 本文知识点:单一职责原则 说明:因为时间紧张,本人写博客过程中只是 ...

  6. Arduino的外部中断

    Arduino的中断函数格式为attachInterrupt(interrput,function,mode). attachInterrupt函数用于设置外部中断,有3个参数,interrput表示 ...

  7. PADS Layout VX.2.3 灌铜之后没有显示整块铜皮的原因

    操作系统:Windows 10 x64 工具1:PADS Layout VX.2.3 灌铜之后没有显示整块铜皮,如下图所示: 点击菜单Tools > Options...(快捷键:Ctrl + ...

  8. java的string方法使用

    1.将list转换为","隔开的字符串 //videoIdList值转换成 1,2,3 String videoIds = StringUtils.join(videoIdList ...

  9. [KMP]字符串匹配算法

    算法介绍: KMP是一种用来处理字符串匹配问题的算法,给你两个字符串A.B,让你回答B是否为A的子串,或者A中有多少子串等于B. 这题最暴力的做法是:枚举A中与B相等的子串的左端点,再判断是否与B相等 ...

  10. CentOS 7 系统的安装

    1.进入安装界面 2.选择"Install CentOS 7" 3.进入欢迎界面,默认语言为"English",点击"Continue" 进 ...