- 通过GenericObjectPool和GenericObjectPoolConfig实现对象池的配置和管理,通常涉及以下几个关键步骤:
- 创建GenericObjectPoolConfig实例并配置参数:这包括设置对象池的基本行为,如最大等待时间、空闲时测试、逐出策略等。
- 定义对象工厂:创建一个工厂类,它继承自PooledObjectFactory接口,负责创建和销毁对象。
- 创建GenericObjectPool实例:使用上述配置和工厂类实例化GenericObjectPool。
下面是一个具体的代码示例,展示如何使用Apache Commons Pool库中的GenericObjectPool和GenericObjectPoolConfig来创建一个简单的连接池:
如下代码示例是获取jdbc连接的示例
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionPool {
private final GenericObjectPool<Connection> connectionPool;
public ConnectionPool(String url, String user, String password) {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(10); // 设置最大连接数
poolConfig.setMaxWaitMillis(5000); // 设置最大等待时间
ConnectionFactory factory = new ConnectionFactory(url, user, password);
connectionPool = new GenericObjectPool<>(factory, poolConfig);
}
public Connection getConnection() throws SQLException {
try {
return connectionPool.borrowObject();
} catch (Exception e) {
throw new SQLException("Error borrowing connection from pool", e);
}
}
public void returnConnection(Connection conn) {
try {
connectionPool.returnObject(conn);
} catch (Exception e) {
}
}
static class ConnectionFactory extends BasePooledObjectFactory<Connection> {
private final String url;
private final String user;
private final String password;
public ConnectionFactory(String url, String user, String password) {
this.url = url;
this.user = user;
this.password = password;
}
@Override
public Connection create() throws Exception {
return DriverManager.getConnection(url, user, password);
}
@Override
public PooledObject<Connection> wrap(Connection connection) {
return new DefaultPooledObject<>(connection);
}
}
}
在这个示例中,ConnectionFactory类负责创建数据库连接,而GenericObjectPool则负责管理这些连接的生命周期,包括借用、归还和销毁。