在项目中使用C3P0作为数据库连接池,被技术总监怼了

运维 数据库运维
数据库连接是一项非常关键的、有限的、昂贵的资源,这一点在多用户的网页应用程序中体现得尤为突出。

[[398951]]


本文转载自微信公众号「Java极客技术」,作者鸭血粉丝。转载本文请联系Java极客技术公众号。

 一、介绍

数据库连接是一项非常关键的、有限的、昂贵的资源,这一点在多用户的网页应用程序中体现得尤为突出。

记得之前做的一个项目,当时的应用程序配置的c3p0数据库连接池,最大允许的连接数是500,结果上线没多久,并发量直接上来了,导致大量的数据插入失败,当晚的心情可想而知~

从那一次事故之后,让我对应用程序的数据库连接数有了一次深刻的认识,为了防止再次栽跟头,特意抽了一个时间来编写程序测试案例,用于测试各个数据源连接池的稳定性,以防止自己再次踩坑!

话不多说,直接撸起来!

二、程序实例

熟悉 web 系统开发的同学,基本都知道,在 Java 生态中开源的常用数据库连接池有以下几种:

  • dbcp:DBCP是一个依赖Jakarta commons-pool对象池机制的数据库连接池,DBCP可以直接的在应用程序中使用,Tomcat的数据源使用的就是DBCP
  • c3p0:c3p0是一个开放源代码的JDBC连接池,它在lib目录中与Hibernate一起发布,包括了实现jdbc3和jdbc2扩展规范说明的Connection和Statement池的DataSources对象
  • druid:阿里出品,淘宝和支付宝专用数据库连接池,但它不仅仅是一个数据库连接池,它还包含一个ProxyDriver,一系列内置的JDBC组件库,一个SQL Parser。支持所有JDBC兼容的数据库,包括Oracle、MySql、Derby、Postgresql、SQL Server、H2等等。

今天我们就一起来对比一下,这三种数据源连接池的稳定性。

2.1、创建测试表

下面以 mysql 数据库为例,首先创建一个t_test表,方面后续进行插入数据操作。

  1. CREATE TABLE t_test ( 
  2.   id bigint(20) unsigned NOT NULL COMMENT '主键ID'
  3.   name varchar(32) NOT NULL COMMENT '名称'
  4.   PRIMARY KEY (id) 
  5. ) ENGINE=InnoDB COMMENT='测试表'

2.2、 编写测试用例

以dbcp为例,首先创建一个dbcp-jdbc.properties配置文件。

  1. username=root 
  2. password=Hello@123456 
  3. driverClassName=com.mysql.jdbc.Driver 
  4. url=jdbc:mysql://192.168.31.200:3306/testdb?useUnicode=true&characterEncoding=UTF-8 
  5. initialSize=5 
  6. maxActive=1000 
  7. maxIdle=5 
  8. removeAbandoned=ture 
  9. removeAbandonedTimeout=20 
  10. logAbandoned=true 
  11. maxWait=100 

接着,创建一个连接池工具DbcpJdbcUtil。

  1. public class DbcpJdbcUtil { 
  2.   
  3.  private static final Logger logger = LoggerFactory.getLogger(DbcpJdbcUtil.class); 
  4.   
  5.  /**jdbc配置文件*/ 
  6.  private static Properties prop = new Properties();  
  7.   
  8.  private static BasicDataSource dataSource = null
  9.  // 它是事务专用连接! 
  10.  private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); 
  11.   
  12.  static { 
  13.   classPathSourceRead(); 
  14.  } 
  15.  
  16.     private static void classPathSourceRead(){ 
  17.      //读取指定位置的配置文档(读取class目录文件) 
  18.      try { 
  19.       logger.info("jdbc路径:" + SysConstants.getValue()); 
  20.    prop.load(DbcpJdbcUtil.class.getClassLoader().getResourceAsStream(SysConstants.getValue())); 
  21.    logger.info("数据配置信息" + JSON.toJSONString(prop)); 
  22.    logger.info("初始化默认jdbc配置文件成功!"); 
  23.   } catch (Exception e) { 
  24.    logger.error("初始化默认jdbc文件失败!",e); 
  25.   } 
  26.     } 
  27.      
  28.  /** 
  29.   * 从连接池获取数据源 
  30.   * @return 
  31.   * @throws Exception 
  32.   */ 
  33.  public static BasicDataSource getDataSource() throws Exception { 
  34.   try { 
  35.    if (dataSource == null) { 
  36.     synchronized (DbcpJdbcUtil.class) { 
  37.      if (dataSource == null) { 
  38.       dataSource = new BasicDataSource(); 
  39.       dataSource.setUsername(prop.getProperty("username")); 
  40.       dataSource.setPassword(prop.getProperty("password")); 
  41.       dataSource.setDriverClassName(prop.getProperty("driverClassName")); 
  42.       dataSource.setUrl(prop.getProperty("url")); 
  43.       dataSource.setInitialSize(Integer.valueOf(prop.getProperty("initialSize"))); 
  44.       dataSource.setMaxActive(Integer.valueOf(prop.getProperty("maxActive"))); 
  45.       dataSource.setMaxIdle(Integer.valueOf(prop.getProperty("maxIdle"))); 
  46.       dataSource.setRemoveAbandoned(Boolean.valueOf(prop.getProperty("removeAbandoned"))); 
  47.       dataSource.setRemoveAbandonedTimeout(Integer.valueOf(prop.getProperty("removeAbandonedTimeout"))); 
  48.       dataSource.setLogAbandoned(Boolean.valueOf(prop.getProperty("logAbandoned"))); 
  49.       dataSource.setMaxWait(Integer.valueOf(prop.getProperty("maxWait"))); 
  50.      } 
  51.     } 
  52.    } 
  53.    return dataSource; 
  54.   } catch (Exception e) { 
  55.    logger.error("根据数据库名称获取数据库资源失败," , e); 
  56.    throw new Exception("根据数据库名称获取数据库资源失败"); 
  57.   } 
  58.  } 
  59.   
  60.  /** 
  61.   * 使用连接池返回一个连接对象 
  62.   *  
  63.   * @return 
  64.   * @throws SQLException 
  65.   */ 
  66.  public static Connection getConnection() throws Exception { 
  67.   try { 
  68.    Connection con = tl.get(); 
  69.    // 当con不等于null,说明已经调用过beginTransaction(),表示开启了事务! 
  70.    if (con != null
  71.     return con; 
  72.    return getDataSource().getConnection(); 
  73.   } catch (Exception e) { 
  74.    logger.error("获取数据库连接失败!", e); 
  75.    throw new SQLException("获取数据库连接失败!"); 
  76.   } 
  77.  } 
  78.   
  79.  /** 
  80.   * 开启事务 1. 获取一个Connection,设置它的setAutoComnmit(false)  
  81.   * 2. 还要保证dao中使用的连接是我们刚刚创建的! --------------  
  82.   * 3. 创建一个Connection,设置为手动提交  
  83.   * 4. 把这个Connection给dao用!  
  84.   * 5. 还要让commitTransaction或rollbackTransaction可以获取到! 
  85.   *  
  86.   * @throws SQLException 
  87.   */ 
  88.  public static void beginTransaction() throws Exception { 
  89.   try { 
  90.    Connection con = tl.get(); 
  91.    if (con != null) { 
  92.     con.close(); 
  93.     tl.remove(); 
  94.     //throw new SQLException("已经开启了事务,就不要重复开启了!"); 
  95.    } 
  96.    con = getConnection(); 
  97.    con.setAutoCommit(false); 
  98.    tl.set(con); 
  99.   } catch (Exception e) { 
  100.    logger.error("数据库事物开启失败!", e); 
  101.    throw new SQLException("数据库事物开启失败!"); 
  102.   } 
  103.  } 
  104.  
  105.  /** 
  106.   * 提交事务 1. 获取beginTransaction提供的Connection,然后调用commit方法 
  107.   *  
  108.   * @throws SQLException 
  109.   */ 
  110.  public static void commitTransaction() throws SQLException { 
  111.   Connection con = tl.get(); 
  112.   try { 
  113.    if (con == null
  114.     throw new SQLException("还没有开启事务,不能提交!"); 
  115.    con.commit(); 
  116.   } catch (Exception e) { 
  117.    logger.error("数据库事物提交失败!", e); 
  118.    throw new SQLException("数据库事物提交失败!"); 
  119.   } finally { 
  120.    if (con != null) { 
  121.     con.close(); 
  122.    } 
  123.    tl.remove(); 
  124.   } 
  125.  } 
  126.   
  127.  /** 
  128.   * 回滚事务 1. 获取beginTransaction提供的Connection,然后调用rollback方法 
  129.   *  
  130.   * @throws SQLException 
  131.   */ 
  132.  public static void rollbackTransaction() throws SQLException { 
  133.   Connection con = tl.get(); 
  134.   try { 
  135.    if (con == null
  136.     throw new SQLException("还没有开启事务,不能回滚!"); 
  137.    con.rollback(); 
  138.   } catch (Exception e) { 
  139.    logger.error("数据库事物回滚失败!", e); 
  140.    throw new SQLException("数据库事物回滚失败!"); 
  141.   } finally { 
  142.    if (con != null) { 
  143.     con.close(); 
  144.    } 
  145.    tl.remove(); 
  146.   } 
  147.  } 
  148.   
  149.  /** 
  150.   * 释放连接  
  151.   * @param connection 
  152.   * @throws SQLException 
  153.   */ 
  154.  public static void releaseConnection(Connection connection) throws SQLException { 
  155.   try { 
  156.    Connection con = tl.get(); 
  157.    // 判断它是不是事务专用,如果是,就不关闭! 如果不是事务专用,那么就要关闭! 
  158.    // 如果con == null,说明现在没有事务,那么connection一定不是事务专用的! 
  159.    //如果con != null,说明有事务,那么需要判断参数连接是否与con相等,若不等,说明参数连接不是事务专用连接 
  160.    if (con == null || con != connection
  161.     connection.close(); 
  162.   } catch (Exception e) { 
  163.    logger.error("数据库连接释放失败!", e); 
  164.    throw new SQLException("数据库连接释放失败!"); 
  165.   } 
  166.  } 
  167.  

最后,编写单元测试程序DBCPTest。

  1. public class DBCPTest { 
  2.   
  3.  private static final int sumCount = 1000000; 
  4.   
  5.  private static final int threadNum = 600; 
  6.   
  7.  private void before(String path) { 
  8.   SysConstants.putValue(path); 
  9.   new DBCPService().insert("delete from t_test"); 
  10.  } 
  11.   
  12.  @Test 
  13.  public void testMysql() { 
  14.   long start = System.currentTimeMillis(); 
  15.   String path = "config/mysql/dbcp-jdbc.properties"
  16.   before(path); 
  17.   for (int i =0; i < 1; i++) { 
  18.    String sql = "insert into t_test(id,name) values('" +i+ "','dbcp-mysql-" + i + "')"
  19.    new DBCPService().insert(sql); 
  20.   } 
  21.   System.out.println("耗时:" + (System.currentTimeMillis() - start)); 
  22.  } 
  23.   
  24.  @Test 
  25.  public void testThreadMysql() throws InterruptedException { 
  26.   String path = "config/mysql/dbcp-jdbc.properties"
  27.   before(path); 
  28.   BlockingQueue<String> queue = new LinkedBlockingQueue<String>(); 
  29.   for (int i = 0; i < sumCount; i++) { 
  30.    String sql = "insert into t_test(id,name) values('" +i+ "','dbcp-mysql-" + i + "')"
  31.    queue.put(sql); 
  32.   } 
  33.   long start = System.currentTimeMillis(); 
  34.   final CountDownLatch countDownLatch = new CountDownLatch(threadNum); 
  35.   for (int i = 0; i < threadNum; i++) { 
  36.    final int finalI = i + 1; 
  37.    new Thread(new Runnable() { 
  38.     @Override 
  39.     public void run() { 
  40.      System.out.println("thread " + finalI + " start"); 
  41.      boolean isGo = true
  42.      while (isGo) { 
  43.       String sql = queue.poll(); 
  44.       if(sql != null) { 
  45.        new DBCPService().insert(sql); 
  46.       }else { 
  47.        isGo =false
  48.        System.out.println("thread " + finalI + " finish"); 
  49.        countDownLatch.countDown(); 
  50.       } 
  51.      } 
  52.     } 
  53.    }).start(); 
  54.   } 
  55.   countDownLatch.await();  
  56.   System.out.println("耗时:" + (System.currentTimeMillis() - start)); 
  57.  } 
  58.  

c3p0、druid的配置也类似,这里就不在重复介绍了!

三、性能测试

程序编写完成之后,下面我们就一起来结合各种不同的场景来测试一下各个数据连接池的表现。

为了进一步扩大测试范围,本次测试还将各个主流的数据库也拉入进去,测试的数据库分别是:mysql-5.7、oracle-12、postgresql-9.6

3.1、插入10万条数据

首先,我们来测试一下,各个数据库插入10万条数据,采用不同的数据源连接池,看看它们的表现如何?

  • 测试dbcp执行结果

  • 测试c3p0执行结果

测试druid执行结果

从上面测试结果,我们可以基本得出如下结论:

  • 从数据连接池性能角度看:dbcp >= druid > c3p0
  • 从数据库性能角度看:oracle > postgresql > mysql

其中druid对postgresql的支持性能最好,c3p0的表现比较差!

3.2、插入100万条数据

可能有的同学,还不太认可,下面我们就来测试一下插入100万条,看看它们的表现如何?

  • 测试dbcp执行结果

  • 测试c3p0执行结果

  • 测试druid执行结果

从上面测试结果,我们可以基本得出如下结论:

  • 从数据连接池性能角度看:druid性能比较稳定,dbcp、c3p0都有某种程度的执行失败
  • 从数据库性能角度看:postgresql > oracle > mysql

还是一样的结论,druid对postgresql的支持性能最好,c3p0的表现比较差!

四、小结

从上面的测试结果,我们可以很清晰的看到,在数据连接池方面,druid和dbcp旗鼓相当,而并发方面druid的稳定性大于dbcp,c3p0相比druid和dbcp,稳定性和执行速度要弱些。

在数据库方面,postgresql速度要优于oracle,而oracle对各个数据源的支持和稳定性要有优势,mysql相比oracle和postgresql,执行速度要弱些。

如果在实际开发中,数据源连接池推荐采用druid,数据库的选用方面 postgresql > oracle > mysql。

 

责任编辑:武晓燕 来源: Java极客技术
相关推荐

2015-10-29 16:59:47

数据库

2021-04-12 07:32:01

数据库

2018-07-20 14:50:43

Java数据库连接池

2009-09-22 17:53:09

Hibernate C

2020-03-04 13:55:28

c3p0数据库连接池

2009-07-15 11:14:30

c3p0连接池

2019-11-27 10:31:51

数据库连接池内存

2010-03-18 15:09:15

python数据库连接

2009-09-22 14:44:18

Hibernate.c

2013-06-17 10:25:16

连接池Java

2009-06-24 07:53:47

Hibernate数据

2022-07-19 13:51:47

数据库Hikari连接池

2015-04-27 09:50:45

Java Hibern连接池详解

2009-08-10 17:34:42

C#数据库连接池

2017-06-22 14:13:07

PythonMySQLpymysqlpool

2009-06-16 09:25:31

JBoss配置

2009-06-17 09:34:31

Hibernate3Hibernate2连接池

2018-10-10 14:27:34

数据库连接池MySQL

2021-08-12 06:52:01

.NET数据库连接池

2020-04-30 14:38:51

数据库连接池线程
点赞
收藏

51CTO技术栈公众号