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

参考:

淘宝连接池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

package taobao_druid;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * The Class DataSourceUtil.
 */
public class DataSourceUtil {

    /** 使用配置文件构建Druid数据源. */
    public static final int DRUID_MYSQL_SOURCE = 0;

    /** 使用配置文件构建Druid数据源. */
    public static final int DRUID_MYSQL_SOURCE2 = 1;

    /** 使用配置文件构建Dbcp数据源. */
    public static final int DBCP_SOURCE = 4;
    public static String confile = "druid.properties";
    public static Properties p = null;

    static {
        p = new Properties();
        InputStream inputStream = null;
        try {
            //java应用
            confile = DataSourceUtil.class.getClassLoader().getResource("").getPath()
                    + confile;
            System.out.println(confile);
            File file = new File(confile);
            inputStream = new BufferedInputStream(new FileInputStream(file));
            p.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据类型获取数据源
     * 
     * @param sourceType
     *            数据源类型
     * @return druid或者dbcp数据源
     * @throws Exception
     *             the exception
     */
    public static final DataSource getDataSource(int sourceType) throws Exception {
        DataSource dataSource = null;
        switch (sourceType) {
        case DRUID_MYSQL_SOURCE:
            dataSource = DruidDataSourceFactory.createDataSource(p);
            break;
        case DRUID_MYSQL_SOURCE2:
            dataSource = DruidDataSourceFactory.createDataSource(p);
            break;
        case DBCP_SOURCE:
            // dataSource = BasicDataSourceFactory.createDataSource(
            // MySqlConfigProperty.getInstance().getProperties());
            break;
        }
        return dataSource;
    }
}


TableOperator

package taobao_druid;

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

import javax.sql.DataSource;

public class TableOperator {
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    private static final int COUNT = 5;

    public TableOperator() {
    }

    public void tearDown() throws Exception {
        try {
            dropTable();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void insert() throws Exception {
        StringBuffer ddl = new StringBuffer();
        ddl.append("INSERT INTO t_big (");
        for (int i = 0; i < COUNT; ++i) {
            if (i != 0) {
                ddl.append(", ");
            }
            ddl.append("F" + i);
        }
        ddl.append(") VALUES (");
        for (int i = 0; i < COUNT; ++i) {
            if (i != 0) {
                ddl.append(", ");
            }
            ddl.append("?");
        }
        ddl.append(")");
        Connection conn = dataSource.getConnection();
        System.out.println(ddl.toString());
        PreparedStatement stmt = conn.prepareStatement(ddl.toString());
        for (int i = 0; i < COUNT; ++i) {
            stmt.setInt(i + 1, i);
        }
        stmt.execute();
        stmt.close();
        conn.close();
    }

    private void dropTable() throws SQLException {
        Connection conn = dataSource.getConnection();
        Statement stmt = conn.createStatement();
        stmt.execute("DROP TABLE t_big");
        stmt.close();
        conn.close();
    }

    public void createTable() throws SQLException {
        StringBuffer ddl = new StringBuffer();
        ddl.append("CREATE TABLE t_big (FID INT ");
        for (int i = 0; i < COUNT; ++i) {
            ddl.append(", ");
            ddl.append("F" + i);
            ddl.append(" varchar2(10)");
        }
        ddl.append(")");
        Connection conn = dataSource.getConnection();
        Statement stmt = conn.createStatement();
        System.out.println(ddl.toString());
        stmt.execute(ddl.toString());
        stmt.close();
        conn.close();
    }
}


MutilThreadTest

package taobao_druid;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class MutilThreadTest {

    public static void main(String argc[]) throws Exception {
        //        test(DataSourceUtil.DBCP_SOURCE, 50);
        test(DataSourceUtil.DRUID_MYSQL_SOURCE, 50);
    }

    public static void test(int dbType, int times) throws Exception {
        int numOfThreads = Runtime.getRuntime().availableProcessors() * 2;
        ExecutorService executor = Executors.newFixedThreadPool(numOfThreads);
        final TableOperator test = new TableOperator();
        // int dbType = DataSourceUtil.DRUID_MYSQL_SOURCE;
        // dbType = DataSourceUtil.DBCP_SOURCE;
        test.setDataSource(DataSourceUtil.getDataSource(dbType));

        boolean createResult = false;
        try {
            test.createTable();
            createResult = true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (createResult) {
            List> results = new ArrayList>();
            for (int i = 0; i < times; i++) {
                results.add(executor.submit(new Callable() {
                    @Override
                    public Long call() throws Exception {
                        long begin = System.currentTimeMillis();
                        try {
                            test.insert();
                            // insertResult = true;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        long end = System.currentTimeMillis();
                        return end - begin;
                    }
                }));
            }
            executor.shutdown();
            while (!executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS))
                ;

            long sum = 0;
            for (Future result : results) {
                sum += result.get();
            }

            System.out.println("---------------db type " + dbType
                    + "------------------");
            System.out.println("number of threads :" + numOfThreads + " times:"
                    + times);
            System.out.println("running time: " + sum + "ms");
            System.out.println("TPS: " + (double) (100000 * 1000)
                    / (double) (sum));
            System.out.println();
            try {
                //                test.tearDown();
                // dropResult = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("初始化数据库失败");
        }

    }

}



src下druid.properties:

driverClassName=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@192.168.97.51:1521:lc8
username=admin8
password=adminpwd8
filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200


你可能感兴趣的:(编程开发)