14

I'm using Apache Commons DBCP. There is a task to track the inner behavior of the DBCP - number of active and idle connections.

I found out that DBCP lacks any such logging at all. Yes, tt is possible to write the code that outputs the status of the BasicDataSource when connection is borrowed from the pool. However there is no way to track the status of the BasicDataSource when connection is returned or closed, because connection object knows nothing about the pool.

Any ideas?

4

4 回答 4

7

我认为方面可能是您的困惑的解决方案。查看:

基本上,您可以编写一个或两个方面来“锁定”DBCP 中某些方法的执行。

就像是:

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;

@Aspect
public class AroundExample {

  @Around("org.apache.commons.dbcp.PoolingDataSource.getConnection()")
  public Object doBasicPStuff(ProceedingJoinPoint pjp) throws Throwable {
    // write code to do what you want
    final PoolingDataSource ds = (PoolingDataSource) pjp.getThis();
    // log whatever you want

    // let it finish
    Object retVal = pjp.proceed();
    // stop stopwatch
    return retVal;
  }

}

这只是一个很小的例子。方面真的很强大,有很多不同的方法可以做你想做的事。该代码取决于您是否使用 Spring,以及您想要记录的内容。

PS我没有测试上面的代码。

于 2010-08-31T01:18:43.287 回答
1

DBCP 的 BasicDataSource 包含一些实际创建池和池工厂的受保护方法。您可以将其子类化并覆盖这些方法以更改行为;例如,获得池工厂或用您自己的工厂替换它。拥有该池后,您就可以在代码中获取池状态。

于 2011-02-17T01:18:08.010 回答
0

AOP 是跟踪池中连接使用情况的方法。但是,它不是很直接。您需要执行以下操作:

  1. 创建一个 ConnectionWrapper 类来包装(装饰器模式)连接并覆盖 close() 方法以另外记录连接 ID、线程 ID 和操作“关闭”
  2. 拦截数据源的 getConnection() 方法。
  3. 在该方法中,记录连接 ID、线程 ID 和操作“打开”
  4. 以同样的方法,装饰原始连接并返回您的 ConnectionWrapper 实例

使用此设置,您可以跟踪从/到池的连接的借用和返回。

于 2012-03-11T04:20:24.123 回答
0

如果您有权访问 DataSource 对象,则可以将其强制转换为 BasicDataSource 并使用and方法获取maxIdleandmaxActive连接。getNumActive()getNumIdle()

于 2015-06-30T14:33:06.320 回答