dbcp 连接池连接示例

本文介绍 dbcp 连接池配置依赖、配置文件和示例代码。

配置依赖

<dependencies>
    <dependency>
        <groupId>com.oceanbase</groupId>
        <artifactId>oceanbase-client</artifactId>
        <version>2.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.7.0</version>
    </dependency>
</dependencies>

配置文件

dbcp.properties 配置文件内容如下:

#驱动名
driverClassName=com.oceanbase.jdbc.Driver
#url
url=jdbc:oceanbase://xxx.xxx.xxx.xxx:1521/?useSSL=false&useServerPrepStmts=true&serverTimezone=UTC
#用户名
username=a****
#密码
password=******
#初试连接数
initialSize=30
#最大活跃数
maxTotal=30
#最大idle数
maxIdle=10
#最小idle数
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
#程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
#removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1

示例代码

工具类

package com.dbcptest;


import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSourceFactory;

/**
 * DBCP 配置类
 * @author SUN
 */
public class KCYDBCPUtil {

    private static Properties properties = new Properties();
    private static DataSource dataSource;
    //加载 DBCP 配置文件
    static{
        try{
            FileInputStream is = new FileInputStream("com.dbcptest/config/dbcp.properties");
            properties.load(is);
        }catch(IOException e){
            e.printStackTrace();
        }

        try{
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //从连接池中获取一个连接
    public static Connection getConnection(){
        Connection connection = null;
        try{
            connection = dataSource.getConnection();
        }catch(SQLException e){
            e.printStackTrace();
        }
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void main(String[] args) {
        getConnection();
    }
}
package com.dbcptest;


import java.sql.Connection;
import java.sql.DriverManager;

public class DBConn {
    private static Connection conn = null;

    //获取一个数据库连接
    public static Connection getConnection() {
        try {
            Class.forName("com.oceanbase.jdbc.Driver");
            DriverManager.registerDriver(new com.oceanbase.jdbc.Driver());
            String dbUrl = "jdbc:oceanbase://xxx.xxx.xxx.xxx:1521/?useSSL=false&useServerPrepStmts=true&serverTimezone=UTC";
            conn = DriverManager.getConnection(dbUrl, "a****", "******");
//            System.out.println("========数据库连接成功========");
        } catch (Exception e) {
            e.printStackTrace();
//            System.out.println("========数据库连接失败========");
            return null;
        }
        return conn;
    }
}

测试类

package com.dbcptest;


import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;


public class DBCPTest {

    //测试,每写一条数据前,就新建一个连接
    @Test
    public void testWriteDBByEveryConn() throws Exception{
        for(int i = 0; i < 20; i++){
            writeDBByEveryConn(i);
        }
        System.out.println("DONE");

    }

    //测试,使用连接池,每写一条数据前,从连接池中获取一个连接
    @Test
    public void testWriteDBByDBCP() throws Exception{
        for(int i = 0; i < 20; i++){
            writeDBByDBCP(i);
        }
        System.out.println("DONE");
    }

    //测试,只建一条连接,写入所有数据
    @Test
    public void testWriteDBByOneConn() throws Exception{
        Connection conn = DBConn.getConnection();
        Statement stat = conn.createStatement();
        for(int i = 0; i < 2000; i++){
            writeDBByOneConn(i, stat);
        }
        conn.close();
        System.out.println("DONE");
    }

    //不使用连接池写数据库,每写一条数据创建一个连接
    public void writeDBByEveryConn(int data){
        String sql = "insert into dbcp values (" + data + ")";
        Connection conn = DBConn.getConnection();
        try{
            Statement stat = conn.createStatement();
            stat.executeUpdate(sql);
        }catch(Exception e){
            e.printStackTrace() ;
        }finally{
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

    //不使用连接池写数据库,只用一个连接,写所有数据
    public void writeDBByOneConn(int data, Statement stat){
        String sql = "insert into dbcp values (" + data + ")";
        try{
            stat.executeUpdate(sql);
        }catch(Exception e){
            e.printStackTrace() ;
        }
    }

    //通过 DBCP 连接池写数据库
    public void writeDBByDBCP(int data){
        String sql = "insert into dbcp values (" + data + ")";
        try {
            Connection conn = KCYDBCPUtil.getConnection();
            Statement stat = conn.createStatement();
            stat.executeUpdate(sql);
            conn.commit();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}