简体   繁体   English

Java中的连接池允许通过JDBC URL进行连接?

[英]Connection pool in java which allows to get connection by jdbc url?

I tried to find the connection pool which allows to get connection by jdbc url but failed. 我试图找到允许通过jdbc url获得连接的连接池,但失败了。 Hikari connection pool doesn't allow do it, the same situation in c3po. Hikari连接池不允许这样做,与c3po中的情况相同。 My use case is: 我的用例是:

ConnectionPool.getConnection(jdbcUrl);

Does anybody know such connection pool in java world? 有人知道Java世界中的这种连接池吗?

A Simple Guide to Connection Pooling in Java Java连接池简单指南

Author - Baeldung 作者-Baeldung

About Author 关于作者

A Simple Implementation 一个简单的实现

To better understand the underlying logic of connection pooling, let's create a simple implementation. 为了更好地理解连接池的基本逻辑,让我们创建一个简单的实现。

Let's start out with a loosely-coupled design, based on just one single interface: 让我们从一个仅基于单个接口的松耦合设计开始:

public interface ConnectionPool {
    Connection getConnection();
    boolean releaseConnection(Connection connection);
    String getUrl();
    String getUser();
    String getPassword();
}

The ConnectionPool interface defines the public API of a basic connection pool. ConnectionPool接口定义基本连接池的公共API。

Now, let's create an implementation, which provides some basic functionality, including getting and releasing a pooled connection: 现在,让我们创建一个实现,该实现提供一些基本功能,包括获取和释放池连接:

public class BasicConnectionPool 
  implements ConnectionPool {

    private String url;
    private String user;
    private String password;
    private List<Connection> connectionPool;
    private List<Connection> usedConnections = new ArrayList<>();
    private static int INITIAL_POOL_SIZE = 10;

    public static BasicConnectionPool create(
      String url, String user, 
      String password) throws SQLException {

        List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE);
        for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
            pool.add(createConnection(url, user, password));
        }
        return new BasicConnectionPool(url, user, password, pool);
    }

    // standard constructors

    @Override
    public Connection getConnection() {
        Connection connection = connectionPool
          .remove(connectionPool.size() - 1);
        usedConnections.add(connection);
        return connection;
    }

    @Override
    public boolean releaseConnection(Connection connection) {
        connectionPool.add(connection);
        return usedConnections.remove(connection);
    }

    private static Connection createConnection(
      String url, String user, String password) 
      throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }

    public int getSize() {
        return connectionPool.size() + usedConnections.size();
    }

    // standard getters
}

Connection pooling is a well-known data access pattern, whose main purpose is to reduce the overhead involved in performing database connections and read/write database operations. 连接池是一种众所周知的数据访问模式,其主要目的是减少执行数据库连接和读/写数据库操作所涉及的开销。

In a nutshell, a connection pool is, at the most basic level, a database connection cache implementation, which can be configured to suit specific requirements. 简而言之,连接池是最基本的数据库连接缓存实现,可以将其配置为适合特定要求。

In this tutorial, we'll make a quick roundup of a few popular connection pooling frameworks, and we'll learn how to implement from scratch our own connection pool. 在本教程中,我们将快速概述一些流行的连接池框架,并且将学习如何从头开始实现我们自己的连接池。

Why Connection Pooling? 为什么要建立连接池?

The question is rhetorical, of course. 当然,这个问题是修辞。

If we analyze the sequence of steps involved in a typical database connection life cycle, we'll understand why: 如果我们分析典型数据库连接生命周期中涉及的步骤顺序,我们将理解原因:

Opening a connection to the database using the database driver Opening a TCP socket for reading/writing data Reading / writing data over the socket Closing the connection Closing the socket It becomes evident that database connections are fairly expensive operations, and as such, should be reduced to a minimum in every possible use case (in edge cases, just avoided). 使用数据库驱动程序打开与数据库的连接打开用于读取/写入数据的TCP套接字通过套接字读取/写入数据关闭连接关闭套接字很明显,数据库连接是相当昂贵的操作,因此应减少在每种可能的使用情况下(在极端情况下,都应避免)。

Here's where connection pooling implementations come into play. 这是连接池实现起作用的地方。

By just simply implementing a database connection container, which allows us to reuse a number of existing connections, we can effectively save the cost of performing a huge number of expensive database trips, hence boosting the overall performance of our database-driven applications. 通过简单地实现一个数据库连接容器,使我们能够重用许多现有连接,我们可以有效地节省执行大量昂贵的数据库行程的成本,从而提高我们数据库驱动的应用程序的整体性能。

JDBC Connection Pooling Frameworks JDBC连接池框架

From a pragmatic perspective, implementing a connection pool from the ground up is just pointless, considering the number of “enterprise-ready” connection pooling frameworks available out there. 从务实的角度来看,考虑到可用的“企业就绪”连接池框架的数量,从头开始实施连接池是没有意义的。

From a didactic one, which is the goal of this article, it's not. 从说教的角度出发,这不是本文的目标。

Even so, before we learn how to implement a basic connection pool, let's first showcase a few popular connection pooling frameworks. 即便如此,在我们学习如何实现基本连接池之前,让我们首先展示一些流行的连接池框架。

Apache Commons DBCP Apache Commons DBCP

public class DBCPDataSource {

    private static BasicDataSource ds = new BasicDataSource();

    static {
        ds.setUrl("jdbc:h2:mem:test");
        ds.setUsername("user");
        ds.setPassword("password");
        ds.setMinIdle(5);
        ds.setMaxIdle(10);
        ds.setMaxOpenPreparedStatements(100);
    }

    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    private DBCPDataSource(){ }
}

In this case, we've used a wrapper class with a static block to easily configure DBCP's properties. 在这种情况下,我们使用了带有静态块的包装器类来轻松配置DBCP的属性。

Here's how to get a pooled connection with the DBCPDataSource class: 以下是使用DBCPDataSource类获得池化连接的方法:

connection con = DBCPDataSource.getConnection();

HikariCP HikariCP

public class HikariCPDataSource {

    private static HikariConfig config = new HikariConfig();
    private static HikariDataSource ds;

    static {
        config.setJdbcUrl("jdbc:h2:mem:test");
        config.setUsername("user");
        config.setPassword("password");
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        ds = new HikariDataSource(config);
    }

    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    private HikariCPDataSource(){}
}

Similarly, here's how to get a pooled connection with the HikariCPDataSource class: 同样,以下是与HikariCPDataSource类获得池化连接的方法:

Connection con = HikariCPDataSource.getConnection();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM