分享

大量数据情况下单线程插入和多线程insert数据库的性能测试

 陈永正的图书馆 2016-11-23

之前一直没有遇到过大批量数据入库的场景,所以一直没有思考过在大量数据的情况下单线程插入和多线程插入的性能情况。今天在看一个项目源代码的时候发现使用了多线程insert操作。

于是简单的写了一个测试程序来测试一批数据在N个线程下的insert情况。

public class ThreadImport {
    private String url="jdbc:oracle:thin:@localhost:1521:orcl";
    private String user="cmis";
    private String password="cmis";
    public Connection getConnect(){
        Connection con = null;
         try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con=DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
         return con;
    }
    public void multiThreadImport( final int ThreadNum){
        final CountDownLatch cdl= new CountDownLatch(ThreadNum);
        long starttime=System.currentTimeMillis();
        for(int k=1;k<=ThreadNum;k++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Connection con=getConnect();
                    try {
                        Statement st=con.createStatement();
                        for(int i=1;i<=80000/ThreadNum;i++){
                            String uuid=UUID.randomUUID().toString();
                            st.addBatch("insert into demo_table(a,b) values('"+uuid+"','"+uuid+"')");
                            if(i%500==0){
                                st.executeBatch();
                            }
                        }
                        cdl.countDown();
                    } catch (Exception e) {
                    }finally{
                        try {
                            con.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
        try {
            cdl.await();
            long spendtime=System.currentTimeMillis()-starttime;
            System.out.println( ThreadNum+"个线程花费时间:"+spendtime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {
        ThreadImport ti=new ThreadImport();
        ti.multiThreadImport(1);
        ti.multiThreadImport(5);
        ti.multiThreadImport(8);
        ti.multiThreadImport(10);
        ti.multiThreadImport(20);
        ti.multiThreadImport(40);
        System.out.println("笔记本CPU数:"+Runtime.getRuntime().availableProcessors());
    }

}

运行结果:

1个线程花费时间:56707
5个线程花费时间:21688
8个线程花费时间:16625
10个线程花费时间:16098
20个线程花费时间:19882
40个线程花费时间:23536
笔记本CPU数:8

发现在一定数量的线程下性能提升的还是很明显。

在实际的项目中,使用了连接池的情况下,多线程(在一定范围内)数据插入的性能还要明显一点。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多