我试图弄清楚当前打开了多少个连接,但我似乎找不到一个明显的方法来使用 Hikari 来做到这一点。
HikariPool
公开该信息 ( getActiveConnections
) 但我看不到从HikariDataSource
.
我试图弄清楚当前打开了多少个连接,但我似乎找不到一个明显的方法来使用 Hikari 来做到这一点。
HikariPool
公开该信息 ( getActiveConnections
) 但我看不到从HikariDataSource
.
如果您使用的是弹簧靴:
new HikariDataSourcePoolMetadata(dataSource).getActive();
您必须通过 JMX 编程访问来获取它。registerMbeans
首先,通过属性或调用来启用 MBean 注册setRegisterMeans()
。然后查阅此页面以了解如何执行编程访问:
https://github.com/brettwooldridge/HikariCP/wiki/JMX-Monitoring
您可以使用以下类进行更好的监控:
import javax.sql.DataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.pool.HikariPool;
import lombok.extern.slf4j.Slf4j;
@Aspect
@Component
@Slf4j
public class DataSourceAspectLogger {
private HikariPool pool;
@Autowired
private HikariDataSource ds;
@Before("execution(* com.x.common.sql.repo.*.*(..))")
public void logBeforeConnection(JoinPoint jp) throws Throwable {
logDataSourceInfos("Before", jp);
}
@After("execution(* com.x.common.sql.repo.*.*(..)) ")
public void logAfterConnection(JoinPoint jp) throws Throwable {
logDataSourceInfos("After", jp);
}
@Autowired
public void getPool() {
try {
java.lang.reflect.Field field = ds.getClass().getDeclaredField("pool");
field.setAccessible(true);
this.pool = (HikariPool) field.get(ds);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void logDataSourceInfos(final String time, final JoinPoint jp) {
final String method = String.format("%s:%s", jp.getTarget().getClass().getName(), jp.getSignature().getName());
int totalConnections = pool.getTotalConnections();
int activeConnections = pool.getActiveConnections();
int freeConnections = totalConnections - activeConnections;
int connectionWaiting = pool.getThreadsAwaitingConnection();
log.info(String.format("%s %s: number of connections in use by the application (active): %d.", time, method, activeConnections));
log.info(String.format("%s %s: the number of established but idle connections: %d.", time, method, freeConnections));
log.info(String.format("%s %s: number of threads waiting for a connection: %d.", time, method, connectionWaiting));
log.info(String.format("%s %s: max pool size: %d.", time, method, ds.getMaximumPoolSize()));
}
}