大量数据情况下单线程插入和多线程insert数据库的性能测试
之前一直没有遇到过大批量数据入库的场景,所以一直没有思考过在大量数据的情况下单线程插入和多线程插入的性能情况。今天在看一个项目源代码的时候发现使用了多线程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
发现在一定数量的线程下性能提升的还是很明显。
在实际的项目中,使用了连接池的情况下,多线程(在一定范围内)数据插入的性能还要明显一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)