我正在试图找出目前有多少个连接被打开,而且我似乎无法找到一个明显的方法来与Hikari一起做。
HikariPool
公开了这些信息(getActiveConnections
),但我没有看到从HikariDataSrouce
访问该信息的简便方法。
答案 0 :(得分:2)
您必须通过JMX程序访问才能获得它。首先,通过registerMbeans
属性或通过调用setRegisterMeans()
启用MBean注册。然后,请参阅此页面以了解如何执行编程访问:
https://github.com/brettwooldridge/HikariCP/wiki/JMX-Monitoring
答案 1 :(得分:1)
如果您使用的是弹簧靴:
new HikariDataSourcePoolMetadata(dataSource).getActive();
答案 2 :(得分:0)
您可以使用下面的类进行更好的监视:
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()));
}
}