在使用 Oracle 时,我可以 Spring 使用 getPooledConnection 而不是来自数据源的 getConnection 吗?

Can I have Spring use getPooledConnection instead getConnection from the Datasource when using Oracle?

我在一个简单的 spring 启动应用程序中有以下代码...

@Bean
public DataSource getDatasource(){
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName(driver);
    ds.setUsername(username);
    ds.setUrl(url);
    ds.setPassword(password);
    return ds;
}

效果很好,但我想要连接池,所以我改为...

@Bean
public DataSource getDatasource(){
    try{
        OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
        ds.setDriverType("thin");
        ds.setUser(username);
        ds.setNetworkProtocol("tcp");
        ds.setPassword(password);
        ds.setDatabaseName(dbName);
        ds.setServerName(serverName);
        return ds;
    } catch (SQLException throwables) {
        logger.error(throwables);
        System.exit(-1);
    }
    return null;
}

但是从文档看来 getConnection 只是 returns 一个本地连接,我需要配置 Spring 来调用 getPooledConnection

是否有我可以创建的另一个 bean 或我可以创建的其他方法?

看起来如果您使用 Oracle 执行此操作,您应该使用称为 UCP 或通用连接池的库...

<dependency>
    <groupId>com.oracle.database.jdbc</groupId>
    <artifactId>ucp</artifactId>
    <version>21.1.0.0</version>
</dependency>

然后我用它来创建数据源,例如...

PoolDataSource ds = PoolDataSourceFactory.getPoolDataSource();
ds.setConnectionFactoryClassName(OracleDataSource.class.getName());
ds.setURL(url);
ds.setUser(username);
ds.setPassword(password);
ds.setInitialPoolSize(1);
ds.setMinPoolSize(1);
ds.setMaxPoolSize(10);
return ds;

我正在完成测试以确保它按预期工作。

要使用通用连接池 (UCP),您需要在类路径中 ucp.jar。例子参考UCPSample.java