今天就跟大家聊聊有关怎么在MySql中插入千万级大数据,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
第一步,读取文件,开始插入多线程
在这里,达到一定量的量是个需要斟酌的问题,在我的实验中,开始使用100w作为这个量,但是出现了新的问题,Java 堆内存溢出,最终采用了10W作为量的标准。
当然,可以有其他的量,看大家自己喜欢那个了。
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import preprocess.ImportDataBase;
public class MuiltThreadImportDB {
private static int m_record = 99999;
private static BufferedReader br = null;
private ArrayList<String> list;
private static int m_thread = 0;
static {
try {
br = new BufferedReader(
new FileReader(
"E:/tianci/IJCAI15 Data/data_format1/user_log_format1.csv"),8192);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
br.readLine(); // 去掉CSV Header
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
String line;
int count = 0;
list = new ArrayList<String>(m_record + 1);
synchronized (br) {
try {
while ((line = br.readLine()) != null) {
if (count < m_record) {
list.add(line);
count++;
} else {
list.add(line);
count = 0;
Thread t1 = new Thread(new MultiThread(list),Integer.toString(m_thread++));
t1.start();
list = new ArrayList<String>(m_record + 1);
}
}
if (list != null) {
Thread t1 = new Thread(new MultiThread(list),Integer.toString(m_thread++));
t1.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new MuiltThreadImportDB().start();
}
}
第二步,使用多线程,批量插入数据
class MultiThread implements Runnable {
private ArrayList<String> list;
public MultiThread(ArrayList<String> list) {
this.list = list;
}
public void run() {
try {
ImportDataBase insert = new ImportDataBase(list);
insert.start();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
display(this.list);
}
public void display(List<String> list) {
// for (String str : list) {
// System.out.println(str);
// }
System.out.print(Thread.currentThread().getName() + " :");
System.out.println(list.size());
}
}
批量操作中,使用mysql的prepareStatement类,当然也使用了statement类的批量操作,性能比不上前者。前者可以达到1w+每秒的插入速度,后者只有2000+;
public int insertUserBehaviour(ArrayList<String> sqls) throws SQLException {
String sql = "insert into user_behaviour_log (user_id,item_id,cat_id,merchant_id,brand_id,time_stamp,action_type)"
+ " values(?,?,?,?,?,?,?)";
preStmt = conn.prepareStatement(sql);
for (int i = 0; i < sqls.size(); i++) {
UserLog log =new UserLog(sqls.get(i));
preStmt.setString(1, log.getUser_id());
preStmt.setString(2, log.getItem_id());
preStmt.setString(3, log.getCat_id());
preStmt.setString(4, log.getMerchant_id());
preStmt.setString(5, log.getBrand_id());
preStmt.setString(6, log.getTimeStamp());
preStmt.setString(7, log.getActionType());
preStmt.addBatch();
if ((i + 1) % 10000 == 0) {
preStmt.executeBatch();
conn.commit();
preStmt.clearBatch();
}
}
preStmt.executeBatch();
conn.commit();
return 1;
}
看完上述内容,你们对怎么在MySql中插入千万级大数据有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。