学习DBCP和C3PO的简单使用

时间:2020-04-26
本文章向大家介绍学习DBCP和C3PO的简单使用,主要包括学习DBCP和C3PO的简单使用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

第一步:创建maven项目

  pom文件内容为

 1  <dependencies>
 2         <!-- 添加oracle jdbc driver -->
 3         <dependency>
 4             <groupId>cn.easyproject</groupId>
 5             <artifactId>ojdbc6</artifactId>
 6             <version>12.1.0.2.0</version>
 7         </dependency>
 8 
 9         <dependency>
10             <groupId>commons-dbcp</groupId>
11             <artifactId>commons-dbcp</artifactId>
12             <version>1.4</version>
13         </dependency>
14 
15         <dependency>
16             <groupId>c3p0</groupId>
17             <artifactId>c3p0</artifactId>
18             <version>0.9.1.2</version>
19         </dependency>
20 
21         <dependency>
22             <groupId>commons-dbutils</groupId>
23             <artifactId>commons-dbutils</artifactId>
24             <version>1.4</version>
25         </dependency>
26     </dependencies>

第二步:创建表和实体类

  

/*
create table STUDENT
        (
        id   CHAR(32) not null,
        name VARCHAR2(64)
        )
        */
public class Student {
    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

第三步:配置DBCP、C3P0

  DBCP的配置文件dbcpconfig.properties

#连接设置
driverClassName=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
username=c##dss
password=123456

#初始化连接
initialSize=10
#最大连接数量
maxActive=20
#最大空闲连接
maxIdle=20
#最小空闲连接
minIdle=5

  C3P0的配置文件c3p0-config.xml

<c3p0-config>
    <!-- 默认配置,如果没有指定则使用这个配置 -->
    <default-config>
        <property name="driverClass">oracle.jdbc.OracleDriver</property>
        <property name="jdbcUrl">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
        <property name="user">c##dss</property>
        <property name="password">123456</property>
        <!-- 初始化池大小 -->
        <property name="initialPoolSize">10</property>
        <!-- 最大空闲时间 -->
        <property name="maxIdleTime">30</property>
        <!-- 最多有多少个连接 -->
        <property name="maxPoolSize">20</property>
        <!-- 最少几个连接 -->
        <property name="minPoolSize">10</property>
        <!-- 每次最多可以执行多少个批处理语句 -->
        <property name="maxStatements">50</property>
    </default-config>
</c3p0-config>

第四步:编写DBCP工具类、C3P0工具类

public class DatadbcpUtil {
    private static BasicDataSource dataSource;

    static {
        try {
            InputStream in = DatadbcpUtil.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties props = new Properties();
            props.load(in);
            dataSource =(BasicDataSource) BasicDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);
        }
    }

    /**
     * 获取DataSource对象
     * @return
     */
    public static BasicDataSource getDataSource() {
        return dataSource;
    }

}
public class DataC3p0Util {
    private static ComboPooledDataSource ds = null;
    static {
        ds = new ComboPooledDataSource();//读取默认配置文件
    }
    public static ComboPooledDataSource getDataSource() {
        return ds;
    }
    public static Connection getConnection() {
        Connection con = null;
        if(con==null) {
            try {
                con = ds.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return con;
    }

}

第五步:编写main

  方便对比两种连接池性能,用线程各自运行对比

public class DBCPorC3PO {

    public static void main(String[] arg0) throws Exception {
        int n = 5;
        long startTime = System.currentTimeMillis();
        CountDownLatch latch=new CountDownLatch(n);
        for(int i=0;i<n;i++){
            //Thread t = new Thread (new C3P0Thread("Thread_"+i,latch));
            Thread t = new Thread (new DBCPThread("Thread_"+i,latch));
            t.start ();
        }
        latch.await();
        System.out.println("耗时" + (System.currentTimeMillis() - startTime));
    }
}

class C3P0Thread implements Runnable {
    String name ;
    CountDownLatch latch;
    C3P0Thread(String name,CountDownLatch latch){
        this.name=name;
        this.latch=latch;
    }
    public void run() {
        try {
            System.out.println("运行" + name);
            for(int i = 5; i > 0; i--) {
                QueryRunner queryRunner = new QueryRunner(DataC3p0Util.getDataSource());
                List<Student> list = queryRunner.query("select * from student t", new BeanListHandler<Student>(Student.class));
            }
            latch.countDown();
            System.out.println("结束" + name);
        }catch (Exception e) {
        }
    }
}

class DBCPThread implements Runnable {
    String name ;
    CountDownLatch latch;
    DBCPThread(String name,CountDownLatch latch){
        this.name=name;
        this.latch=latch;
    }
    public void run() {
        try {
            System.out.println("运行" + name);
            for(int i = 5; i > 0; i--) {
                QueryRunner queryRunner = new QueryRunner(DatadbcpUtil.getDataSource());
                List<Student> list = queryRunner.query("select * from student t", new BeanListHandler<Student>(Student.class));
            }
            latch.countDown();
            System.out.println("结束" + name);
        }catch (Exception e) {
        }
    }
}

总结:

  使用方法主要在DataSource.getConnection来获得链接。分开运行后取得结果

  DBCP C3P0
模拟5个线程循环10次并发访问数据库 用时1181ms 用时860ms
模拟10个线程循环10次并发访问数据库 用时1188ms 用时953ms
模拟100个线程循环10次并发访问数据库 用时1641ms 用时2703ms
模拟1000个线程循环10次并发访问数据库 用时5187ms 用时12563ms
模拟5000个线程循环10次并发访问数据库 用时23610ms 用时22032ms

  详细配置

  参数
DBCP dataSource: 要连接的 datasource (通常我们不会定义在 server.xml)
defaultAutoCommit: 对于事务是否 autoCommit, 默认值为 true
defaultReadOnly: 对于数据库是否只能读取, 默认值为 false
driverClassName:连接数据库所用的 JDBC Driver Class,
maxActive: 可以从对象池中取出的对象最大个数,为0则表示没有限制,默认为8
maxIdle: 最大等待连接中的数量,设 0 为没有限制 (对象池中对象最大个数)
minIdle:对象池中对象最小个数
maxWait: 最大等待秒数, 单位为 ms, 超过时间会丟出错误信息
password: 登陆数据库所用的密码
url: 连接数据库的 URL
username: 登陆数据库所用的帐号
validationQuery: 验证连接是否成功, SQL SELECT 指令至少要返回一行
removeAbandoned: 是否自我中断, 默认是 false
removeAbandonedTimeout: 几秒后会自我中断, removeAbandoned 必须为 true
logAbandoned: 是否记录中断事件, 默认为 false
minEvictableIdleTimeMillis:大于0 ,进行连接空闲时间判断,或为0,对空闲的连接不进行验证;默认30分钟
timeBetweenEvictionRunsMillis:失效检查线程运行时间间隔,如果小于等于0,不会启动检查线程,默认-1
testOnBorrow:取得对象时是否进行验证,检查对象是否有效,默认为false
testOnReturn:返回对象时是否进行验证,检查对象是否有效,默认为false
testWhileIdle:空闲时是否进行验证,检查对象是否有效,默认为false
initialSize:初始化线程数
C3P0 acquireIncrement: 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3
acquireRetryAttempts: 定义在从数据库获取新连接失败后重复尝试的次数。Default: 30
acquireRetryDelay: 两次连接中间隔时间,单位毫秒。Default: 1000
autoCommitOnClose: 连接关闭时默认将所有未提交的操作回滚。Defaul t: false 
automaticTestTable: c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么属性preferredTestQuery将被忽略。你不 能在这张Test表上进行任何操作,它将只供c3p0测试使用。Default: null
breakAfterAcquireFailure: 获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连 接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。Default: false
checkoutTimeout:当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限期等待。单位毫秒。Default: 0
connectionTesterClassName: 通过实现ConnectionTester或QueryConnectionT ester的类来测试连接。类名需制定全路径。Default: com.mchange.v2.c3p0.impl.Def aultConnectionTester
factoryClassLocation: 指定c3p0 libraries的路径,如果(通常都是这样)在本地即可获得那么无需设置,默认null即可Default: null
idleConnectionTestPeriod: 每60秒检查所有连接池中的空闲连接。Defaul t: 0
initialPoolSize: 初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3
maxIdleTime: 最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0
maxPoolSize: 连接池中保留的最大连接数。Default: 15
maxStatements: JDBC的标准参数,用以控制数据源内加载的PreparedSt atements数量。但由于预缓存的statements属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。如 果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0
maxStatementsPerConnection: maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0
numHelperThreads:c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能通过多线程实现多个操作同时被执行。Default: 3
overrideDefaultUser:当用户调用getConnection()时使root用户成为去获取连接的用户。主要用于连接池连接非c3p0的数据源时。Default: null
overrideDefaultPassword:与overrideDefaultUser参数对应使用的一个参数。Default: null
password:密码。Default: null
user:用户名。Default: null
preferredTestQuery:定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意:测试的表必须在初始数据源的时候就存在。Default: null
propertyCycle:用户修改系统配置参数执行前最多等待300秒。Defaul t: 300 
testConnectionOnCheckout:因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交 的时候都将校验其有效性。建议使用idleConnectio nTestPeriod或automaticTestTable等方法来提升连接测试的性能。Default: false 
testConnectionOnCheckin:如果设为true那么在取得连接的同时将校验连接的有效性。Default: false

原文地址:https://www.cnblogs.com/xujf/p/12769700.html