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

时间:2025-02-07 19:29:00

之前一直没有遇到过大批量数据入库的场景,所以一直没有思考过在大量数据的情况下单线程插入和多线程插入的性能情况。今天在看一个项目源代码的时候发现使用了多线程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 {
            ("");
            con=(url, user, password);
        } catch (Exception e) {
            ();
        }
         return con;
    }
    public void multiThreadImport( final int ThreadNum){
        final CountDownLatch cdl= new CountDownLatch(ThreadNum);
        long starttime=();
        for(int k=1;k<=ThreadNum;k++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Connection con=getConnect();
                    try {
                        Statement st=();
                        for(int i=1;i<=80000/ThreadNum;i++){
                            String uuid=().toString();
                            ("insert into demo_table(a,b) values('"+uuid+"','"+uuid+"')");
                            if(i%500==0){
                                ();
                            }
                        }
                        ();
                    } catch (Exception e) {
                    }finally{
                        try {
                            ();
                        } catch (SQLException e) {
                            ();
                        }
                    }
                }
            }).start();
        }
        try {
            ();
            long spendtime=()-starttime;
            ( ThreadNum+"个线程花费时间:"+spendtime);
        } catch (InterruptedException e) {
            ();
        }

    }

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

}

运行结果:

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

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

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