淘宝druid数据库连接池使用示例

来源:互联网 发布:都玩网络ko三国 编辑:程序博客网 时间:2024/04/28 12:20

参考:

淘宝连接池Druid  http://www.zhurouyoudu.com/index.PHP/archives/635/

http://code.alibabatech.com/wiki/display/Druid/Home

druid使用 http://blog.csdn.net/yunnysunny/article/details/8657095

Mybatis整合Druid和H2嵌入式数据库 http://my.oschina.net/u/580483/blog/91435

druid-0.2.19.jar只支持JDK1.6以上

DataSourceUtil

[java] view plain copy
  1. package taobao_druid;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.util.Properties;  
  9.   
  10. import javax.sql.DataSource;  
  11.   
  12. import com.alibaba.druid.pool.DruidDataSourceFactory;  
  13.   
  14. /** 
  15.  * The Class DataSourceUtil. 
  16.  */  
  17. public class DataSourceUtil {  
  18.   
  19.     /** 使用配置文件构建Druid数据源. */  
  20.     public static final int DRUID_MYSQL_SOURCE = 0;  
  21.   
  22.     /** 使用配置文件构建Druid数据源. */  
  23.     public static final int DRUID_MYSQL_SOURCE2 = 1;  
  24.   
  25.     /** 使用配置文件构建Dbcp数据源. */  
  26.     public static final int DBCP_SOURCE = 4;  
  27.     public static String confile = "druid.properties";  
  28.     public static Properties p = null;  
  29.   
  30.     static {  
  31.         p = new Properties();  
  32.         InputStream inputStream = null;  
  33.         try {  
  34.             //java应用  
  35.             confile = DataSourceUtil.class.getClassLoader().getResource("").getPath()  
  36.                     + confile;  
  37.             System.out.println(confile);  
  38.             File file = new File(confile);  
  39.             inputStream = new BufferedInputStream(new FileInputStream(file));  
  40.             p.load(inputStream);  
  41.         } catch (Exception e) {  
  42.             e.printStackTrace();  
  43.         } finally {  
  44.             try {  
  45.                 if (inputStream != null) {  
  46.                     inputStream.close();  
  47.                 }  
  48.             } catch (IOException e) {  
  49.                 e.printStackTrace();  
  50.             }  
  51.         }  
  52.     }  
  53.   
  54.     /** 
  55.      * 根据类型获取数据源 
  56.      *  
  57.      * @param sourceType 
  58.      *            数据源类型 
  59.      * @return druid或者dbcp数据源 
  60.      * @throws Exception 
  61.      *             the exception 
  62.      */  
  63.     public static final DataSource getDataSource(int sourceType) throws Exception {  
  64.         DataSource dataSource = null;  
  65.         switch (sourceType) {  
  66.         case DRUID_MYSQL_SOURCE:  
  67.             dataSource = DruidDataSourceFactory.createDataSource(p);  
  68.             break;  
  69.         case DRUID_MYSQL_SOURCE2:  
  70.             dataSource = DruidDataSourceFactory.createDataSource(p);  
  71.             break;  
  72.         case DBCP_SOURCE:  
  73.             // dataSource = BasicDataSourceFactory.createDataSource(  
  74.             // MySqlConfigProperty.getInstance().getProperties());  
  75.             break;  
  76.         }  
  77.         return dataSource;  
  78.     }  
  79. }  


TableOperator

[java] view plain copy
  1. package taobao_druid;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.PreparedStatement;  
  5. import java.sql.SQLException;  
  6. import java.sql.Statement;  
  7.   
  8. import javax.sql.DataSource;  
  9.   
  10. public class TableOperator {  
  11.     private DataSource dataSource;  
  12.   
  13.     public void setDataSource(DataSource dataSource) {  
  14.         this.dataSource = dataSource;  
  15.     }  
  16.   
  17.     private static final int COUNT = 5;  
  18.   
  19.     public TableOperator() {  
  20.     }  
  21.   
  22.     public void tearDown() throws Exception {  
  23.         try {  
  24.             dropTable();  
  25.         } catch (SQLException e) {  
  26.             e.printStackTrace();  
  27.         }  
  28.     }  
  29.   
  30.     public void insert() throws Exception {  
  31.         StringBuffer ddl = new StringBuffer();  
  32.         ddl.append("INSERT INTO t_big (");  
  33.         for (int i = 0; i < COUNT; ++i) {  
  34.             if (i != 0) {  
  35.                 ddl.append(", ");  
  36.             }  
  37.             ddl.append("F" + i);  
  38.         }  
  39.         ddl.append(") VALUES (");  
  40.         for (int i = 0; i < COUNT; ++i) {  
  41.             if (i != 0) {  
  42.                 ddl.append(", ");  
  43.             }  
  44.             ddl.append("?");  
  45.         }  
  46.         ddl.append(")");  
  47.         Connection conn = dataSource.getConnection();  
  48.         System.out.println(ddl.toString());  
  49.         PreparedStatement stmt = conn.prepareStatement(ddl.toString());  
  50.         for (int i = 0; i < COUNT; ++i) {  
  51.             stmt.setInt(i + 1, i);  
  52.         }  
  53.         stmt.execute();  
  54.         stmt.close();  
  55.         conn.close();  
  56.     }  
  57.   
  58.     private void dropTable() throws SQLException {  
  59.         Connection conn = dataSource.getConnection();  
  60.         Statement stmt = conn.createStatement();  
  61.         stmt.execute("DROP TABLE t_big");  
  62.         stmt.close();  
  63.         conn.close();  
  64.     }  
  65.   
  66.     public void createTable() throws SQLException {  
  67.         StringBuffer ddl = new StringBuffer();  
  68.         ddl.append("CREATE TABLE t_big (FID INT ");  
  69.         for (int i = 0; i < COUNT; ++i) {  
  70.             ddl.append(", ");  
  71.             ddl.append("F" + i);  
  72.             ddl.append(" varchar2(10)");  
  73.         }  
  74.         ddl.append(")");  
  75.         Connection conn = dataSource.getConnection();  
  76.         Statement stmt = conn.createStatement();  
  77.         System.out.println(ddl.toString());  
  78.         stmt.execute(ddl.toString());  
  79.         stmt.close();  
  80.         conn.close();  
  81.     }  
  82. }  


MutilThreadTest

[java] view plain copy
  1. package taobao_druid;  
  2.   
  3. import java.sql.SQLException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import java.util.concurrent.Callable;  
  7. import java.util.concurrent.ExecutorService;  
  8. import java.util.concurrent.Executors;  
  9. import java.util.concurrent.Future;  
  10. import java.util.concurrent.TimeUnit;  
  11.   
  12. public class MutilThreadTest {  
  13.   
  14.     public static void main(String argc[]) throws Exception {  
  15.         //        test(DataSourceUtil.DBCP_SOURCE, 50);  
  16.         test(DataSourceUtil.DRUID_MYSQL_SOURCE, 50);  
  17.     }  
  18.   
  19.     public static void test(int dbType, int times) throws Exception {  
  20.         int numOfThreads = Runtime.getRuntime().availableProcessors() * 2;  
  21.         ExecutorService executor = Executors.newFixedThreadPool(numOfThreads);  
  22.         final TableOperator test = new TableOperator();  
  23.         // int dbType = DataSourceUtil.DRUID_MYSQL_SOURCE;  
  24.         // dbType = DataSourceUtil.DBCP_SOURCE;  
  25.         test.setDataSource(DataSourceUtil.getDataSource(dbType));  
  26.   
  27.         boolean createResult = false;  
  28.         try {  
  29.             test.createTable();  
  30.             createResult = true;  
  31.         } catch (SQLException e) {  
  32.             e.printStackTrace();  
  33.         }  
  34.         if (createResult) {  
  35.             List<Future<Long>> results = new ArrayList<Future<Long>>();  
  36.             for (int i = 0; i < times; i++) {  
  37.                 results.add(executor.submit(new Callable<Long>() {  
  38.                     @Override  
  39.                     public Long call() throws Exception {  
  40.                         long begin = System.currentTimeMillis();  
  41.                         try {  
  42.                             test.insert();  
  43.                             // insertResult = true;  
  44.                         } catch (Exception e) {  
  45.                             e.printStackTrace();  
  46.                         }  
  47.                         long end = System.currentTimeMillis();  
  48.                         return end - begin;  
  49.                     }  
  50.                 }));  
  51.             }  
  52.             executor.shutdown();  
  53.             while (!executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS))  
  54.                 ;  
  55.   
  56.             long sum = 0;  
  57.             for (Future<Long> result : results) {  
  58.                 sum += result.get();  
  59.             }  
  60.   
  61.             System.out.println("---------------db type " + dbType  
  62.                     + "------------------");  
  63.             System.out.println("number of threads :" + numOfThreads + " times:"  
  64.                     + times);  
  65.             System.out.println("running time: " + sum + "ms");  
  66.             System.out.println("TPS: " + (double) (100000 * 1000)  
  67.                     / (double) (sum));  
  68.             System.out.println();  
  69.             try {  
  70.                 //                test.tearDown();  
  71.                 // dropResult = true;  
  72.             } catch (Exception e) {  
  73.                 e.printStackTrace();  
  74.             }  
  75.         } else {  
  76.             System.out.println("初始化数据库失败");  
  77.         }  
  78.   
  79.     }  
  80.   
  81. }  



src下druid.properties:

[java] view plain copy
  1. driverClassName=oracle.jdbc.driver.OracleDriver  
  2. url=jdbc:oracle:thin:@192.168.97.51:1521:lc8  
  3. username=admin8  
  4. password=adminpwd8  
  5. filters=stat  
  6. initialSize=2  
  7. maxActive=300  
  8. maxWait=60000  
  9. timeBetweenEvictionRunsMillis=60000  
  10. minEvictableIdleTimeMillis=300000  
  11. validationQuery=SELECT 1  
  12. testWhileIdle=true  
  13. testOnBorrow=false  
  14. testOnReturn=false  
  15. poolPreparedStatements=false  
  16. maxPoolPreparedStatementPerConnectionSize=200  
0 0
原创粉丝点击