如何在JDBC中建立连接池?

llm*_*llm 104 java connection-pooling jdbc

任何人都可以提供有关如何建立JDBC连接池的示例或链接吗?

从搜索谷歌我看到许多不同的方式这样做,这是相当混乱.

最终我需要代码来返回一个java.sql.Connection对象,但我无法入门.欢迎提出任何建议.

更新: 没有javax.sqljava.sql已经汇集连接实现?为什么不最好使用这些?

Pas*_*ent 100

如果你需要一个独立的连接池,我的偏好是通过DBCP转到C3P0(我在之前的回答中提到),我在DBCP负载过重时遇到了太多问题.使用C3P0很简单.从文档:

ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver
cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" );
cpds.setUser("swaldman");
cpds.setPassword("test-password");

// the settings below are optional -- c3p0 can work with defaults
cpds.setMinPoolSize(5);
cpds.setAcquireIncrement(5);
cpds.setMaxPoolSize(20);

// The DataSource cpds is now a fully configured and usable pooled DataSource 
Run Code Online (Sandbox Code Playgroud)

但是,如果您在应用程序服务器内运行,我建议使用它提供的内置连接池.在这种情况下,您需要配置它(请参阅应用程序服务器的文档)并通过JNDI检索DataSource:

DataSource ds = (DataSource) new InitialContext().lookup("jdbc/myDS");
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.甚至不需要去c3p0文档.:) (2认同)

Ale*_*yak 18

不要重新发明轮子.

尝试一下现成的第三方组件:

Apache DBCP提供了有关如何设置池javax.sql.DataSource的不同示例.这是一个可以帮助您入门的示例.


Ten*_*she 18

通常,如果您需要连接池,那么您正在编写在某个托管环境中运行的应用程序,即您正在应用程序服务器中运行.如果是这种情况,确保在尝试任何其他选项之前检查应用程序服务器提供的连接池设施.

开箱即用的解决方案将与其他应用服务器设施最佳集成.但是,如果您没有在应用程序服务器中运行,我会推荐Apache Commons DBCP组件.它被广泛使用,并提供大多数应用程序所需的所有基本池功能.


Eri*_*ser 16

我建议使用commons-dbcp库.有很多关于如何使用它的例子,这里是移动简单的链接.用法很简单:

 BasicDataSource ds = new BasicDataSource();
 ds.setDriverClassName("oracle.jdbc.driver.OracleDriver")
 ds.setUsername("scott");
 ds.setPassword("tiger");
 ds.setUrl(connectURI);
 ...
 Connection conn = ds.getConnection();
Run Code Online (Sandbox Code Playgroud)

您只需要创建一次数据源,因此如果您不知道如何操作,请务必阅读文档.如果您不知道如何正确编写JDBC语句以便不泄漏资源,那么您也可能需要阅读此Wikipedia页面.

  • 这实际上是否创建了连接池? (8认同)

tob*_*jdc 16

HikariCP

它很现代,很快,很简单.我将它用于每个新项目.我比C3P0更喜欢它,不太了解其他池.


Pow*_*ord 7

在应用服务器中,我们使用我工作的地方(我记得Oracle Application Server 10g),池由应用服务器处理.我们javax.sql.DataSource使用带有的JNDI查找来检索javax.sql.InitialContext.

它完成了这样的事情

try {     
   context = new InitialContext();
   jdbcURL = (DataSource) context.lookup("jdbc/CachedDS");
   System.out.println("Obtained Cached Data Source ");
}
catch(NamingException e)   
{  
    System.err.println("Error looking up Data Source from Factory: "+e.getMessage());
}
Run Code Online (Sandbox Code Playgroud)

(我们没有编写此代码,它是从本文档中复制的.)


Yas*_*ash 5

  • 池化机制是提前创建对象的方式.加载类时
  • 它改进了应用程序performance[通过重新使用相同的对象来对对象数据执行任何操作]和memory[分配和解除分配许多对象会产生显着的内存管理开销].
  • 不需要对象清理,因为我们使用相同的Object,减少了垃圾收集负载.

«池[ Object池,String恒定池,Thread池,连接池]

字符串常量池

  • 字符串文字池仅维护每个不同字符串值的一个副本.这必须是不可改变的.
  • 调用实习方法时,它使用equals方法在池中检查具有相同内容的对象可用性.«如果池中有String-copy,则返回引用.«否则,将String对象添加到池中并返回引用.

示例:用于验证池中唯一对象的字符串.

public class StringPoolTest {
    public static void main(String[] args) { // Integer.valueOf(), String.equals()
        String eol = System.getProperty("line.separator"); //java7 System.lineSeparator();

        String s1 = "Yash".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s1, s1.hashCode(), System.identityHashCode(s1));
        String s2 = "Yas"+"h".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s2, s2.hashCode(), System.identityHashCode(s2));
        String s3 = "Yas".intern()+"h".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s3, s3.hashCode(), System.identityHashCode(s3));
        String s4 = "Yas"+"h";
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s4, s4.hashCode(), System.identityHashCode(s4));
    }
}
Run Code Online (Sandbox Code Playgroud)

使用类型4连接池的驱动程序 使用第三方库[ DBCP2,c3p0,Tomcat JDBC]

Type 4 - The Thin driver converts JDBC calls directly into the vendor-specific database protocol Ex[Oracle - Thick, MySQL - Quora]. 维基

在连接池机制中,当加载类时,它获取physical JDBC connection对象并向用户提供包装的物理连接对象.PoolableConnection是实际连接的包装器.

  • getConnection()从连接对象池中选择一个自由包装连接并返回它.
  • close() 而不是关闭它将包装连接返回到池.

示例:将~DBCP2连接池与Java 7 [ try-with-resources]一起使用

public class ConnectionPool {
    static final BasicDataSource ds_dbcp2 = new BasicDataSource();
    static final ComboPooledDataSource ds_c3p0 = new ComboPooledDataSource();
    static final DataSource ds_JDBC = new DataSource();

    static Properties prop = new Properties();
    static {
        try {
            prop.load(ConnectionPool.class.getClassLoader().getResourceAsStream("connectionpool.properties"));

            ds_dbcp2.setDriverClassName( prop.getProperty("DriverClass") );
            ds_dbcp2.setUrl( prop.getProperty("URL") );
            ds_dbcp2.setUsername( prop.getProperty("UserName") );
            ds_dbcp2.setPassword( prop.getProperty("Password") );
            ds_dbcp2.setInitialSize( 5 );

            ds_c3p0.setDriverClass( prop.getProperty("DriverClass") );
            ds_c3p0.setJdbcUrl( prop.getProperty("URL") );
            ds_c3p0.setUser( prop.getProperty("UserName") );
            ds_c3p0.setPassword( prop.getProperty("Password") );
            ds_c3p0.setMinPoolSize(5);
            ds_c3p0.setAcquireIncrement(5);
            ds_c3p0.setMaxPoolSize(20);

            PoolProperties pool = new PoolProperties();
            pool.setUrl( prop.getProperty("URL") );
            pool.setDriverClassName( prop.getProperty("DriverClass") );
            pool.setUsername( prop.getProperty("UserName") );
            pool.setPassword( prop.getProperty("Password") );
            pool.setValidationQuery("SELECT 1");// SELECT 1(mysql) select 1 from dual(oracle)

            pool.setInitialSize(5);
            pool.setMaxActive(3);
            ds_JDBC.setPoolProperties( pool );
        } catch (IOException e) {   e.printStackTrace();
        } catch (PropertyVetoException e) { e.printStackTrace(); }
    }

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

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

    public static Connection getJDBCConnection() throws SQLException {
        return ds_JDBC.getConnection();
    }
}
public static boolean exists(String UserName, String Password ) throws SQLException {
    boolean exist = false;
    String SQL_EXIST = "SELECT * FROM users WHERE username=? AND password=?";
    try ( Connection connection = ConnectionPool.getDBCP2Connection();
          PreparedStatement pstmt = connection.prepareStatement(SQL_EXIST); ) {
        pstmt.setString(1, UserName );
        pstmt.setString(2, Password );

        try (ResultSet resultSet = pstmt.executeQuery()) {
            exist = resultSet.next(); // Note that you should not return a ResultSet here.
        }
    }
    System.out.println("User : "+exist);
    return exist;
}
Run Code Online (Sandbox Code Playgroud)

jdbc:<DB>:<drivertype>:<HOST>:<TCP/IP PORT>:<dataBaseName> jdbc:oracle:thin:@localhost:1521:myDBName jdbc:mysql://localhost:3306/myDBName

connectionpool.properties

URL         : jdbc:mysql://localhost:3306/myDBName
DriverClass : com.mysql.jdbc.Driver
UserName    : root
Password    :
Run Code Online (Sandbox Code Playgroud)

Web应用程序:为了避免连接问题,所有连接都关闭[MySQL"wait_timeout"默认为8小时],以便重新打开与底层数据库的连接.

你可以通过设置testOnBorrow = true和validationQuery ="SELECT 1"来测试每个连接,并且不要使用autoReconnect for MySQL server,因为它已被弃用.问题

===== ===== context.xml ===== =====
<?xml version="1.0" encoding="UTF-8"?>
<!-- The contents of this file will be loaded for a web application -->
<Context>
    <Resource name="jdbc/MyAppDB" auth="Container" 
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" 
        type="javax.sql.DataSource" 

        initialSize="5" minIdle="5" maxActive="15" maxIdle="10"

        testWhileIdle="true"
            timeBetweenEvictionRunsMillis="30000"

        testOnBorrow="true"
            validationQuery="SELECT 1"
            validationInterval="30000"


        driverClassName="com.mysql.jdbc.Driver" 
        url="jdbc:mysql://localhost:3306/myDBName" 
        username="yash" password="777"
    />
</Context>

===== ===== web.xml ===== =====
<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/MyAppDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>
===== ===== DBOperations ===== =====
servlet «   init() {}
Normal call used by sevlet  « static {}

static DataSource ds;
static {
    try {
        Context ctx=new InitialContext();
        Context envContext = (Context)ctx.lookup("java:comp/env");
        ds  =   (DataSource) envContext.lookup("jdbc/MyAppDB");
    } catch (NamingException e) {   e.printStackTrace();    }
}
Run Code Online (Sandbox Code Playgroud)

另见:


blu*_*uar 5

在2017年底,Proxool,BoneCP,C3P0,DBCP现已绝迹。HikariCP(创建于2012年)似乎很有前途,让我知道的其他一切都没了。 http://www.baeldung.com/hikaricp

Proxool存在许多问题:
-在高负载下可能超过连接的最大数量,并且不能返回到最大以下
-即使连接过期后也可以设法不返回最小连接数
-可以锁定整个池(以及所有服务器/客户端线程)如果在HouseKeeper线程期间无法连接数据库(不使用.setQueryTimeout)-HouseKeeper
线程在对其进程进行连接池锁定的同时,请求Prototyper线程重新创建连接(清除),这可能导致争用条件/锁定。在这些方法调用中,循环中的最后一个参数应始终为sweep:false,仅在其下面的sweep:true。
-HouseKeeper最后只需要进行一次PrototypeController扫描,并具有更多[上述]
-HouseKeeper线程在查看哪些连接可能过期之前会检查连接的测试[测试过期的连接的风险可能会由于防火墙中DB的其他超时而断开/终止等。]
-项目的代码未完成(已定义的属性但未采取任何措施)
-如果未定义,则默认最大连接寿命为4小时(过多)
-HouseKeeper线程每个池每五秒钟运行一次(过多)。

您可以修改代码并进行这些改进。但是,由于它是2003年创建的,并于2008年进行了更新,因此它缺少将近10年的Java改进,而hikaricp等解决方案都无法利用它。