zoukankan      html  css  js  c++  java
  • Dbcp 数据源配置

    Dbcp最基础的数据源Apache的开源项目,dbcp最后更新停留在2010年,在dbcp基础上衍生出dbcp2截止当前最新更新在2020年。

    一:添加依赖

           <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-dbcp2</artifactId>
                <version>${dbcp.version}</version>
            </dependency> 
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>            

    二:添加配置文件dbcp.properties,所有参数在org.apache.commons.dbcp2.BasicDataSourceFactory工厂类中都有定义

    #全部的参数参考,org.apache.commons.dbcp2.BasicDataSourceFactory里的ALL_PROPERTIES
    driverClassName=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/test
    username=root
    password=
    
    #<!-- 初始化连接 -->
    initialSize=10
    #最大连接数量
    maxActive=50
    #<!-- 最大空闲连接 -->
    maxIdle=20
    #<!-- 最小空闲连接 -->
    minIdle=5
    #<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
    maxWait=60000
    
    #JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] 
    #注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
    connectionProperties=useUnicode=true;characterEncoding=gbk;serverTimezone=UTC
    #指定由连接池所创建的连接的自动提交(auto-commit)状态。
    defaultAutoCommit=true
    #driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
    #可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
    defaultTransactionIsolation=READ_UNCOMMITTED
    

     三:创建数据源对象

    import java.io.FileInputStream;
    import java.util.Properties;
    
    import org.apache.commons.dbcp2.BasicDataSource;
    import org.apache.commons.dbcp2.BasicDataSourceFactory;
    
    /***
     * 
     * @author zhanchaohan
     *
     */
    public class DbcpUtill {
        public BasicDataSource initBasicDataSource() throws Exception {
            Properties properties = new Properties();
            properties.load(new FileInputStream(DbcpUtill.class.getResource("/dbcp.properties").getPath()));
    //        BasicDataSourceFactory bsf = new BasicDataSourceFactory();// 创建工厂
    
            return BasicDataSourceFactory.createDataSource(properties);// 获取数据源
        }
    }

    四:官方给出了三个实例

    4.1:BasicDataSourceExample.java

    package com.jachs.dbcp.apache;
    
    /*
     * Licensed to the Apache Software Foundation (ASF) under one or more
     * contributor license agreements.  See the NOTICE file distributed with
     * this work for additional information regarding copyright ownership.
     * The ASF licenses this file to You under the Apache License, Version 2.0
     * (the "License"); you may not use this file except in compliance with
     * the License.  You may obtain a copy of the License at
     * 
     *      http://www.apache.org/licenses/LICENSE-2.0
     * 
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import javax.sql.DataSource;
    
    //
    // Here are the dbcp-specific classes.
    // Note that they are only used in the setupDataSource
    // method. In normal use, your classes interact
    // only with the standard JDBC API
    //
    import org.apache.commons.dbcp2.BasicDataSource;
    
    //
    // Here's a simple example of how to use the BasicDataSource.
    //
    
    //
    // Note that this example is very similar to the PoolingDriver
    // example.
    
    //
    // To compile this example, you'll want:
    //  * commons-pool-2.3.jar
    //  * commons-dbcp-2.1.jar 
    // in your classpath.
    //
    // To run this example, you'll want:
    //  * commons-pool-2.3.jar
    //  * commons-dbcp-2.1.jar 
    //  * commons-logging-1.2.jar
    // in your classpath.
    //
    //
    // Invoke the class using two arguments:
    //  * the connect string for your underlying JDBC driver
    //  * the query you'd like to execute
    // You'll also want to ensure your underlying JDBC driver
    // is registered.  You can use the "jdbc.drivers"
    // property to do this.
    //
    // For example:
    //  java -Djdbc.drivers=org.h2.Driver 
    //       -classpath commons-pool2-2.3.jar:commons-dbcp2-2.1.jar:commons-logging-1.2.jar:h2-1.3.152.jar:. 
    //       BasicDataSourceExample 
    //       "jdbc:h2:~/test" 
    //       "SELECT 1"
    //
    public class BasicDataSourceExample {
    
        public static void main(String[] args) {
            // First we set up the BasicDataSource.
            // Normally this would be handled auto-magically by
            // an external configuration, but in this example we'll
            // do it manually.
            //
            System.out.println("Setting up data source.");
            DataSource dataSource = setupDataSource(args[0]);
            System.out.println("Done.");
    
            //
            // Now, we can use JDBC DataSource as we normally would.
            //
            Connection conn = null;
            Statement stmt = null;
            ResultSet rset = null;
    
            try {
                System.out.println("Creating connection.");
                conn = dataSource.getConnection();
                System.out.println("Creating statement.");
                stmt = conn.createStatement();
                System.out.println("Executing statement.");
                rset = stmt.executeQuery(args[1]);
                System.out.println("Results:");
                int numcols = rset.getMetaData().getColumnCount();
                while(rset.next()) {
                    for(int i=1;i<=numcols;i++) {
                        System.out.print("	" + rset.getString(i));
                    }
                    System.out.println("");
                }
            } catch(SQLException e) {
                e.printStackTrace();
            } finally {
                try { if (rset != null) rset.close(); } catch(Exception e) { }
                try { if (stmt != null) stmt.close(); } catch(Exception e) { }
                try { if (conn != null) conn.close(); } catch(Exception e) { }
            }
        }
    
        public static DataSource setupDataSource(String connectURI) {
            BasicDataSource ds = new BasicDataSource();
            ds.setDriverClassName("org.h2.Driver");
            ds.setUrl(connectURI);
            return ds;
        }
    
        public static void printDataSourceStats(DataSource ds) {
            BasicDataSource bds = (BasicDataSource) ds;
            System.out.println("NumActive: " + bds.getNumActive());
            System.out.println("NumIdle: " + bds.getNumIdle());
        }
    
        public static void shutdownDataSource(DataSource ds) throws SQLException {
            BasicDataSource bds = (BasicDataSource) ds;
            bds.close();
        }
    }
    View Code

    4.2:PoolingDataSourceExample.java

    package com.jachs.dbcp.apache;
    /*
     * Licensed to the Apache Software Foundation (ASF) under one or more
     * contributor license agreements.  See the NOTICE file distributed with
     * this work for additional information regarding copyright ownership.
     * The ASF licenses this file to You under the Apache License, Version 2.0
     * (the "License"); you may not use this file except in compliance with
     * the License.  You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    import javax.sql.DataSource;
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    //
    // Here are the dbcp-specific classes.
    // Note that they are only used in the setupDataSource
    // method. In normal use, your classes interact
    // only with the standard JDBC API
    //
    import org.apache.commons.pool2.ObjectPool;
    import org.apache.commons.pool2.impl.GenericObjectPool;
    import org.apache.commons.dbcp2.ConnectionFactory;
    import org.apache.commons.dbcp2.PoolableConnection;
    import org.apache.commons.dbcp2.PoolingDataSource;
    import org.apache.commons.dbcp2.PoolableConnectionFactory;
    import org.apache.commons.dbcp2.DriverManagerConnectionFactory;
    
    //
    // Here's a simple example of how to use the PoolingDataSource.
    //
    
    //
    // Note that this example is very similar to the PoolingDriver
    // example.  In fact, you could use the same pool in both a
    // PoolingDriver and a PoolingDataSource
    //
    
    //
    // To compile this example, you'll want:
    //  * commons-pool2-2.3.jar
    //  * commons-dbcp2-2.1.jar
    // in your classpath.
    //
    // To run this example, you'll want:
    //  * commons-pool2-2.3.jar
    //  * commons-dbcp2-2.1.jar
    //  * commons-logging-1.2.jar
    //  * the classes for your (underlying) JDBC driver
    // in your classpath.
    //
    // Invoke the class using two arguments:
    //  * the connect string for your underlying JDBC driver
    //  * the query you'd like to execute
    // You'll also want to ensure your underlying JDBC driver
    // is registered.  You can use the "jdbc.drivers"
    // property to do this.
    //
    // For example:
    //  java -Djdbc.drivers=org.h2.Driver 
    //       -classpath commons-pool2-2.3.jar:commons-dbcp2-2.1.jar:commons-logging-1.2.jar:h2-1.3.152.jar:. 
    //       PoolingDataSourceExample 
    //       "jdbc:h2:~/test" 
    //       "SELECT 1"
    //
    public class PoolingDataSourceExample {
    
        public static void main(String[] args) {
            //
            // First we load the underlying JDBC driver.
            // You need this if you don't use the jdbc.drivers
            // system property.
            //
            System.out.println("Loading underlying JDBC driver.");
            try {
                Class.forName("org.h2.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            System.out.println("Done.");
    
            //
            // Then, we set up the PoolingDataSource.
            // Normally this would be handled auto-magically by
            // an external configuration, but in this example we'll
            // do it manually.
            //
            System.out.println("Setting up data source.");
            DataSource dataSource = setupDataSource(args[0]);
            System.out.println("Done.");
    
            //
            // Now, we can use JDBC DataSource as we normally would.
            //
            Connection conn = null;
            Statement stmt = null;
            ResultSet rset = null;
    
            try {
                System.out.println("Creating connection.");
                conn = dataSource.getConnection();
                System.out.println("Creating statement.");
                stmt = conn.createStatement();
                System.out.println("Executing statement.");
                rset = stmt.executeQuery(args[1]);
                System.out.println("Results:");
                int numcols = rset.getMetaData().getColumnCount();
                while(rset.next()) {
                    for(int i=1;i<=numcols;i++) {
                        System.out.print("	" + rset.getString(i));
                    }
                    System.out.println("");
                }
            } catch(SQLException e) {
                e.printStackTrace();
            } finally {
                try { if (rset != null) rset.close(); } catch(Exception e) { }
                try { if (stmt != null) stmt.close(); } catch(Exception e) { }
                try { if (conn != null) conn.close(); } catch(Exception e) { }
            }
        }
    
        public static DataSource setupDataSource(String connectURI) {
            //
            // First, we'll create a ConnectionFactory that the
            // pool will use to create Connections.
            // We'll use the DriverManagerConnectionFactory,
            // using the connect string passed in the command line
            // arguments.
            //
            ConnectionFactory connectionFactory =
                new DriverManagerConnectionFactory(connectURI,null);
    
            //
            // Next we'll create the PoolableConnectionFactory, which wraps
            // the "real" Connections created by the ConnectionFactory with
            // the classes that implement the pooling functionality.
            //
            PoolableConnectionFactory poolableConnectionFactory =
                new PoolableConnectionFactory(connectionFactory, null);
    
            //
            // Now we'll need a ObjectPool that serves as the
            // actual pool of connections.
            //
            // We'll use a GenericObjectPool instance, although
            // any ObjectPool implementation will suffice.
            //
            ObjectPool<PoolableConnection> connectionPool =
                    new GenericObjectPool<>(poolableConnectionFactory);
            
            // Set the factory's pool property to the owning pool
            poolableConnectionFactory.setPool(connectionPool);
    
            //
            // Finally, we create the PoolingDriver itself,
            // passing in the object pool we created.
            //
            PoolingDataSource<PoolableConnection> dataSource =
                    new PoolingDataSource<>(connectionPool);
    
            return dataSource;
        }
    }
    View Code

    4.3:PoolingDriverExample.java

    package com.jachs.dbcp.apache;
    /*
     * Licensed to the Apache Software Foundation (ASF) under one or more
     * contributor license agreements.  See the NOTICE file distributed with
     * this work for additional information regarding copyright ownership.
     * The ASF licenses this file to You under the Apache License, Version 2.0
     * (the "License"); you may not use this file except in compliance with
     * the License.  You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import org.apache.commons.dbcp2.ConnectionFactory;
    import org.apache.commons.dbcp2.DriverManagerConnectionFactory;
    import org.apache.commons.dbcp2.PoolableConnection;
    import org.apache.commons.dbcp2.PoolableConnectionFactory;
    import org.apache.commons.dbcp2.PoolingDriver;
    //
    // Here are the dbcp-specific classes.
    // Note that they are only used in the setupDriver
    // method. In normal use, your classes interact
    // only with the standard JDBC API
    //
    import org.apache.commons.pool2.ObjectPool;
    import org.apache.commons.pool2.impl.GenericObjectPool;
    
    //
    // Here's a simple example of how to use the PoolingDriver.
    //
    
    // To compile this example, you'll want:
    //  * commons-pool-2.3.jar
    //  * commons-dbcp-2.1.jar 
    // in your classpath.
    //
    // To run this example, you'll want:
    //  * commons-pool-2.3.jar
    //  * commons-dbcp-2.1.jar 
    //  * commons-logging-1.2.jar
    // in your classpath.
    //
    // Invoke the class using two arguments:
    //  * the connect string for your underlying JDBC driver
    //  * the query you'd like to execute
    // You'll also want to ensure your underlying JDBC driver
    // is registered.  You can use the "jdbc.drivers"
    // property to do this.
    //
    // For example:
    //  java -Djdbc.drivers=org.h2.Driver 
    //       -classpath commons-pool2-2.3.jar:commons-dbcp2-2.1.jar:commons-logging-1.2.jar:h2-1.3.152.jar:. 
    //       PoolingDriverExample 
    //       "jdbc:h2:~/test" 
    //       "SELECT 1"
    //
    public class PoolingDriverExample {
    
        public static void main(String[] args) {
            //
            // First we load the underlying JDBC driver.
            // You need this if you don't use the jdbc.drivers
            // system property.
            //
            System.out.println("Loading underlying JDBC driver.");
            try {
                Class.forName("org.h2.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            System.out.println("Done.");
    
            //
            // Then we set up and register the PoolingDriver.
            // Normally this would be handled auto-magically by
            // an external configuration, but in this example we'll
            // do it manually.
            //
            System.out.println("Setting up driver.");
            try {
                setupDriver(args[0]);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Done.");
    
            //
            // Now, we can use JDBC as we normally would.
            // Using the connect string
            //  jdbc:apache:commons:dbcp:example
            // The general form being:
            //  jdbc:apache:commons:dbcp:<name-of-pool>
            //
    
            Connection conn = null;
            Statement stmt = null;
            ResultSet rset = null;
    
            try {
                System.out.println("Creating connection.");
                conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:example");
                System.out.println("Creating statement.");
                stmt = conn.createStatement();
                System.out.println("Executing statement.");
                rset = stmt.executeQuery(args[1]);
                System.out.println("Results:");
                int numcols = rset.getMetaData().getColumnCount();
                while(rset.next()) {
                    for(int i=1;i<=numcols;i++) {
                        System.out.print("	" + rset.getString(i));
                    }
                    System.out.println("");
                }
            } catch(SQLException e) {
                e.printStackTrace();
            } finally {
                try { if (rset != null) rset.close(); } catch(Exception e) { }
                try { if (stmt != null) stmt.close(); } catch(Exception e) { }
                try { if (conn != null) conn.close(); } catch(Exception e) { }
            }
    
            // Display some pool statistics
            try {
                printDriverStats();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // closes the pool
            try {
                shutdownDriver();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void setupDriver(String connectURI) throws Exception {
            //
            // First, we'll create a ConnectionFactory that the
            // pool will use to create Connections.
            // We'll use the DriverManagerConnectionFactory,
            // using the connect string passed in the command line
            // arguments.
            //
            ConnectionFactory connectionFactory =
                new DriverManagerConnectionFactory(connectURI,null);
    
            //
            // Next, we'll create the PoolableConnectionFactory, which wraps
            // the "real" Connections created by the ConnectionFactory with
            // the classes that implement the pooling functionality.
            //
            PoolableConnectionFactory poolableConnectionFactory =
                new PoolableConnectionFactory(connectionFactory, null);
    
            //
            // Now we'll need a ObjectPool that serves as the
            // actual pool of connections.
            //
            // We'll use a GenericObjectPool instance, although
            // any ObjectPool implementation will suffice.
            //
            ObjectPool<PoolableConnection> connectionPool =
                new GenericObjectPool<>(poolableConnectionFactory);
            
            // Set the factory's pool property to the owning pool
            poolableConnectionFactory.setPool(connectionPool);
    
            //
            // Finally, we create the PoolingDriver itself...
            //
            Class.forName("org.apache.commons.dbcp2.PoolingDriver");
            PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
    
            //
            // ...and register our pool with it.
            //
            driver.registerPool("example",connectionPool);
    
            //
            // Now we can just use the connect string "jdbc:apache:commons:dbcp:example"
            // to access our pool of Connections.
            //
        }
    
        public static void printDriverStats() throws Exception {
            PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
            ObjectPool<? extends Connection> connectionPool = driver.getConnectionPool("example");
    
            System.out.println("NumActive: " + connectionPool.getNumActive());
            System.out.println("NumIdle: " + connectionPool.getNumIdle());
        }
    
        public static void shutdownDriver() throws Exception {
            PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
            driver.closePool("example");
        }
    }
    View Code
  • 相关阅读:
    【基础】jquery全选、反选、全不选代码
    【基础】jquery全选、反选、全不选代码
    收集一些程序员励志经典名言
    收集一些程序员励志经典名言
    收集一些程序员励志经典名言
    防止表单重复提交的解决方案整理
    Git使用教程
    2019牛客暑期多校训练营(第二场)J Subarray
    Hibernate-配置
    与项目欧拉速度比较:C vs Python与Erlang vs Haskell
  • 原文地址:https://www.cnblogs.com/zhanchaohan/p/14694466.html
Copyright © 2011-2022 走看看