监控空闲连接数 ,活动连接,总连接数,等待连接的线程数是非常短暂的。由于每个统计数据都是时间敏感的,并且是独立收集的,所以在短时间内可能无法“累计”。不要基于这些值进行任何编程决策,它们仅用于监视。
代码语言:javascript复制@Slf4j
public class DataSourceMonitor {
private HikariPoolMXBean proxy;
private boolean hasStarted;
@Resource
private HikariDataSource hikariDataSource;
@Scheduled(cron = "0/1 * * * * *")
public void monitor() {
try {
if (null == proxy) {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (" hikariDataSource.getPoolName() ")");
proxy = JMX.newMXBeanProxy(mBeanServer, poolName, HikariPoolMXBean.class);
} else {
log.info("{}, {}, {}, {}", proxy.getTotalConnections(), proxy.getActiveConnections(), proxy.getIdleConnections(), proxy.getThreadsAwaitingConnection());
}
} catch (Throwable cause) {
log.error("fail》》", cause);
}
}
}
配置
代码语言:javascript复制spring.datasource.hikari.register-mbeans=true
必须得至少获取一个连接, 不然会一直报错
代码语言:javascript复制java.lang.reflect.UndeclaredThrowableException: null
at com.sun.proxy.$Proxy174.getTotalConnections(Unknown Source) ~[?:?]
at com.bestpay.redbag.web.controller.MrathenaController.datasource(MrathenaController.java:38) ~[classes/:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_202]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_202]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_202]
at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_202]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[?:1.8.0_202]
可配调整如下配置来测试效果
代码语言:javascript复制spring.datasource.hikari.maximum-pool-size=50
spring.datasource.hikari.minimum-idle=50
spring.datasource.hikari.connection-timeout=250
监控 Hikari 连接数的最好实现方式是,参考 源码logPoolState
代码语言:javascript复制/**
* @see HikariPool#logPoolState(java.lang.String...)
*/
public static String poolState(HikariDataSource dataSource, boolean ifLog, String... prefix) {
String poolName = dataSource.getPoolName();
HikariPoolMXBean mx = dataSource.getHikariPoolMXBean();
String format = String.format("%s - %sstats (total=%d, active=%d, idle=%d, waiting=%d)",
poolName, (prefix.length > 0 ? prefix[0] : ""),
mx.getTotalConnections(), mx.getActiveConnections(), mx.getIdleConnections(), mx.getThreadsAwaitingConnection());
return format;
}