导入:Java实现大批量数据导入导出(100W以上)

阅读文本大概需要3分钟。

来源:https://www.cnblogs.com/barrywxx/p/10700221.html

最近业务方有一个需求,需要一次导入超过100万数据到系统数据库。可能大家首先会想,这么大的数据,干嘛通过程序去实现导入,为什么不直接通过SQL导入到数据库。

一、为什么一定要在代码实现

说说为什么不能通过SQL直接导入到数据库,而是通过程序实现:

1. 首先,这个导入功能开始提供页面导入,只是开始业务方保证的一次只有<3W的数据导入;

2. 其次,业务方导入的内容需要做校验,比如门店号,商品号等是否系统存在,需要程序校验;

3. 最后,业务方导入的都是编码,数据库中还要存入对应名称,方便后期查询,SQL导入也是无法实现的。

基于以上上三点,就无法直接通过SQL语句导入数据库。那就只能老老实实的想办法通过程序实现。

二、程序实现有以下技术难点

1. 一次读取这么大的数据量,肯定会导致服务器内存溢出;

2. 调用接口保存一次传输数据量太大,网络传输压力会很大;

3. 最终通过SQL一次批量插入,对数据库压力也比较大,如果业务同时操作这个表数据,很容易造成死锁。

三、解决思路

根据列举的技术难点我的解决思路是:

1. 既然一次读取整个导入文件,那就先将文件流上传到服务器磁盘,然后分批从磁盘读取(支持多线程读取),这样就防止内存溢出;

2. 调用插入数据库接口也是根据分批读取的内容进行调用;

3. 分批插入数据到数据库。

四、具体实现代码

1. 流式上传文件到服务器磁盘

 略,一般Java上传就可以实现,这里就不贴出。

2. 多线程分批从磁盘读取

批量读取文件:

  1. import org.slf4j.Logger;

  2. import org.slf4j.LoggerFactory;

  3. import java.io.File;

  4. import java.io.FileNotFoundException;

  5. import java.io.RandomAccessFile;

  6. import java.nio.ByteBuffer;

  7. import java.nio.channels.FileChannel;

  8. /**

  9. * 类功能描述:批量读取文件

  10. *

  11. * @author WangXueXing create at 19-3-14 下午6:47

  12. * @version 1.0.0

  13. */

  14. public class BatchReadFile {

  15. private final Logger LOGGER = LoggerFactory.getLogger(BatchReadFile.class);

  16. /**

  17. * 字符集UTF-8

  18. */

  19. public static final String CHARSET_UTF8 = "UTF-8";

  20. /**

  21. * 字符集GBK

  22. */

  23. public static final String CHARSET_GBK = "GBK";

  24. /**

  25. * 字符集gb2312

  26. */

  27. public static final String CHARSET_GB2312 = "gb2312";

  28. /**

  29. * 文件内容分割符-逗号

  30. */

  31. public static final String SEPARATOR_COMMA = ",";

  32. private int bufSize = 1024;

  33. // 换行符

  34. private byte key = "\n".getBytes()[0];

  35. // 当前行数

  36. private long lineNum = 0;

  37. // 文件编码,默认为gb2312

  38. private String encode = CHARSET_GB2312;

  39. // 具体业务逻辑监听器

  40. private ReaderFileListener readerListener;

  41. public void setEncode(String encode) {

  42. this.encode = encode;

  43. }

  44. public void setReaderListener(ReaderFileListener readerListener) {

  45. this.readerListener = readerListener;

  46. }

  47. /**

  48. * 获取准确开始位置

  49. * @param file

  50. * @param position

  51. * @return

  52. * @throws Exception

  53. */

  54. public long getStartNum(File file, long position) throws Exception {

  55. long startNum = position;

  56. FileChannel fcin = new RandomAccessFile(file, "r").getChannel();

  57. fcin.position(position);

  58. try {

  59. int cache = 1024;

  60. ByteBuffer rBuffer = ByteBuffer.allocate(cache);

  61. // 每次读取的内容

  62. byte[] bs = new byte[cache];

  63. // 缓存

  64. byte[] tempBs = new byte[0];

  65. while (fcin.read(rBuffer) != -1) {

  66. int rSize = rBuffer.position();

  67. rBuffer.rewind();

  68. rBuffer.get(bs);

  69. rBuffer.clear();

  70. byte[] newStrByte = bs;

  71. // 如果发现有上次未读完的缓存,则将它加到当前读取的内容前面

  72. if (null != tempBs) {

  73. int tL = tempBs.length;

  74. newStrByte = new byte[rSize + tL];

  75. System.arraycopy(tempBs, 0, newStrByte, 0, tL);

  76. System.arraycopy(bs, 0, newStrByte, tL, rSize);

  77. }

  78. // 获取开始位置之后的第一个换行符

  79. int endIndex = indexOf(newStrByte, 0);

  80. if (endIndex != -1) {

  81. return startNum + endIndex;

  82. }

  83. tempBs = substring(newStrByte, 0, newStrByte.length);

  84. startNum += 1024;

  85. }

  86. } finally {

  87. fcin.close();

  88. }

  89. return position;

  90. }

  91. /**

  92. * 从设置的开始位置读取文件,一直到结束为止。如果 end设置为负数,刚读取到文件末尾

  93. * @param fullPath

  94. * @param start

  95. * @param end

  96. * @throws Exception

  97. */

  98. public void readFileByLine(String fullPath, long start, long end) throws Exception {

  99. File fin = new File(fullPath);

  100. if (!fin.exists()) {

  101. throw new FileNotFoundException("没有找到文件:" + fullPath);

  102. }

  103. FileChannel fileChannel = new RandomAccessFile(fin, "r").getChannel();

  104. fileChannel.position(start);

  105. try {

  106. ByteBuffer rBuffer = ByteBuffer.allocate(bufSize);

  107. // 每次读取的内容

  108. byte[] bs = new byte[bufSize];

  109. // 缓存

  110. byte[] tempBs = new byte[0];

  111. String line;

  112. // 当前读取文件位置

  113. long nowCur = start;

  114. while (fileChannel.read(rBuffer) != -1) {

  115. int rSize = rBuffer.position();

  116. rBuffer.rewind();

  117. rBuffer.get(bs);

  118. rBuffer.clear();

  119. byte[] newStrByte;

  120. //去掉表头

  121. if(nowCur == start){

  122. int firstLineIndex = indexOf(bs, 0);

  123. int newByteLenth = bs.length-firstLineIndex-1;

  124. newStrByte = new byte[newByteLenth];

  125. System.arraycopy(bs, firstLineIndex+1, newStrByte, 0, newByteLenth);

  126. } else {

  127. newStrByte = bs;

  128. }

  129. // 如果发现有上次未读完的缓存,则将它加到当前读取的内容前面

  130. if (null != tempBs && tempBs.length != 0) {

  131. int tL = tempBs.length;

  132. newStrByte = new byte[rSize + tL];

  133. System.arraycopy(tempBs, 0, newStrByte, 0, tL);

  134. System.arraycopy(bs, 0, newStrByte, tL, rSize);

  135. }

  136. // 是否已经读到最后一位

  137. boolean isEnd = false;

  138. nowCur += bufSize;

  139. // 如果当前读取的位数已经比设置的结束位置大的时候,将读取的内容截取到设置的结束位置

  140. if (end > 0 && nowCur > end) {

  141. // 缓存长度 - 当前已经读取位数 - 最后位数

  142. int l = newStrByte.length - (int) (nowCur - end);

  143. newStrByte = substring(newStrByte, 0, l);

  144. isEnd = true;

  145. }

  146. int fromIndex = 0;

  147. int endIndex = 0;

  148. // 每次读一行内容,以 key(默认为\n) 作为结束符

  149. while ((endIndex = indexOf(newStrByte, fromIndex)) != -1) {

  150. byte[] bLine = substring(newStrByte, fromIndex, endIndex);

  151. line = new String(bLine, 0, bLine.length, encode);

  152. lineNum++;

  153. // 输出一行内容,处理方式由调用方提供

  154. readerListener.outLine(line.trim(), lineNum, false);

  155. fromIndex = endIndex + 1;

  156. }

  157. // 将未读取完成的内容放到缓存中

  158. tempBs = substring(newStrByte, fromIndex, newStrByte.length);

  159. if (isEnd) {

  160. break;

  161. }

  162. }

  163. // 将剩下的最后内容作为一行,输出,并指明这是最后一行

  164. String lineStr = new String(tempBs, 0, tempBs.length, encode);

  165. readerListener.outLine(lineStr.trim(), lineNum, true);

  166. } finally {

  167. fileChannel.close();

  168. fin.deleteOnExit();

  169. }

  170. }

  171. /**

  172. * 查找一个byte[]从指定位置之后的一个换行符位置

  173. *

  174. * @param src

  175. * @param fromIndex

  176. * @return

  177. * @throws Exception

  178. */

  179. private int indexOf(byte[] src, int fromIndex) throws Exception {

  180. for (int i = fromIndex; i < src.length; i++) {

  181. if (src[i] == key) {

  182. return i;

  183. }

  184. }

  185. return -1;

  186. }

  187. /**

  188. * 从指定开始位置读取一个byte[]直到指定结束位置为止生成一个全新的byte[]

  189. *

  190. * @param src

  191. * @param fromIndex

  192. * @param endIndex

  193. * @return

  194. * @throws Exception

  195. */

  196. private byte[] substring(byte[] src, int fromIndex, int endIndex) throws Exception {

  197. int size = endIndex - fromIndex;

  198. byte[] ret = new byte[size];

  199. System.arraycopy(src, fromIndex, ret, 0, size);

  200. return ret;

  201. }

  202. }

以上是关键代码:利用FileChannel与ByteBuffer从磁盘中分批读取数据

多线程调用批量读取: 

  1. /**

  2. * 类功能描述: 线程读取文件

  3. *

  4. * @author WangXueXing create at 19-3-14 下午6:51

  5. * @version 1.0.0

  6. */

  7. public class ReadFileThread extends Thread {

  8. private ReaderFileListener processDataListeners;

  9. private String filePath;

  10. private long start;

  11. private long end;

  12. private Thread preThread;

  13. public ReadFileThread(ReaderFileListener processDataListeners,

  14. long start,long end,

  15. String file) {

  16. this(processDataListeners, start, end, file, null);

  17. }

  18. public ReadFileThread(ReaderFileListener processDataListeners,

  19. long start,long end,

  20. String file,

  21. Thread preThread) {

  22. this.setName(this.getName()+"-ReadFileThread");

  23. this.start = start;

  24. this.end = end;

  25. this.filePath = file;

  26. this.processDataListeners = processDataListeners;

  27. this.preThread = preThread;

  28. }

  29. @Override

  30. public void run() {

  31. BatchReadFile readFile = new BatchReadFile();

  32. readFile.setReaderListener(processDataListeners);

  33. readFile.setEncode(processDataListeners.getEncode());

  34. try {

  35. readFile.readFileByLine(filePath, start, end + 1);

  36. if(this.preThread != null){

  37. this.preThread.join();

  38. }

  39. } catch (Exception e) {

  40. throw new RuntimeException(e);

  41. }

  42. }

  43. }

监听读取:

 

  1. import java.util.ArrayList;

  2. import java.util.List;

  3. /**

  4. * 类功能描述:读文件监听父类

  5. *

  6. * @author WangXueXing create at 19-3-14 下午6:52

  7. * @version 1.0.0

  8. */

  9. public abstract class ReaderFileListener {

  10. // 一次读取行数,默认为1000

  11. private int readColNum = 1000;

  12. /**

  13. * 文件编码

  14. */

  15. private String encode;

  16. /**

  17. * 分批读取行列表

  18. */

  19. private List rowList = new ArrayList<>();

  20. /**

  21. *其他参数

  22. */

  23. private T otherParams;

  24. /**

  25. * 每读取到一行数据,添加到缓存中

  26. * @param lineStr 读取到的数据

  27. * @param lineNum 行号

  28. * @param over 是否读取完成

  29. * @throws Exception

  30. */

  31. public void outLine(String lineStr, long lineNum, boolean over) throws Exception {

  32. if(null != lineStr && !lineStr.trim().equals("")){

  33. rowList.add(lineStr);

  34. }

  35. if (!over && (lineNum % readColNum == 0)) {

  36. output(rowList);

  37. rowList = new ArrayList<>();

  38. } else if (over) {

  39. output(rowList);

  40. rowList = new ArrayList<>();

  41. }

  42. }

  43. /**

  44. * 批量输出

  45. *

  46. * @param stringList

  47. * @throws Exception

  48. */

  49. public abstract void output(List stringList) throws Exception;

  50. /**

  51. * 设置一次读取行数

  52. * @param readColNum

  53. */

  54. protected void setReadColNum(int readColNum) {

  55. this.readColNum = readColNum;

  56. }

  57. public String getEncode() {

  58. return encode;

  59. }

  60. public void setEncode(String encode) {

  61. this.encode = encode;

  62. }

  63. public T getOtherParams() {

  64. return otherParams;

  65. }

  66. public void setOtherParams(T otherParams) {

  67. this.otherParams = otherParams;

  68. }

  69. public List getRowList() {

  70. return rowList;

  71. }

  72. public void setRowList(List rowList) {

  73. this.rowList = rowList;

  74. }

  75. }

实现监听读取并分批调用插入数据接口:

 

  1. import com.today.api.finance.ImportServiceClient;

  2. import com.today.api.finance.request.ImportRequest;

  3. import com.today.api.finance.response.ImportResponse;

  4. import com.today.api.finance.service.ImportService;

  5. import com.today.common.Constants;

  6. import com.today.domain.StaffSimpInfo;

  7. import com.today.util.EmailUtil;

  8. import com.today.util.UserSessionHelper;

  9. import com.today.util.readfile.ReadFile;

  10. import com.today.util.readfile.ReadFileThread;

  11. import com.today.util.readfile.ReaderFileListener;

  12. import org.slf4j.Logger;

  13. import org.slf4j.LoggerFactory;

  14. import org.springframework.beans.factory.annotation.Value;

  15. import org.springframework.stereotype.Service;

  16. import org.springframework.util.StringUtils;

  17. import java.io.File;

  18. import java.io.FileInputStream;

  19. import java.util.ArrayList;

  20. import java.util.Arrays;

  21. import java.util.List;

  22. import java.util.concurrent.FutureTask;

  23. import java.util.stream.Collectors;

  24. /**

  25. * 类功能描述:报表导入服务实现

  26. *

  27. * @author WangXueXing create at 19-3-19 下午1:43

  28. * @version 1.0.0

  29. */

  30. @Service

  31. public class ImportReportServiceImpl extends ReaderFileListener {

  32. private final Logger LOGGER = LoggerFactory.getLogger(ImportReportServiceImpl.class);

  33. @Value("${READ_COL_NUM_ONCE}")

  34. private String readColNum;

  35. @Value("${REPORT_IMPORT_RECEIVER}")

  36. private String reportImportReceiver;

  37. /**

  38. * 财务报表导入接口

  39. */

  40. private ImportService service = new ImportServiceClient();

  41. /**

  42. * 读取文件内容

  43. * @param file

  44. */

  45. public void readTxt(File file, ImportRequest importRequest) throws Exception {

  46. this.setOtherParams(importRequest);

  47. ReadFile readFile = new ReadFile();

  48. try(FileInputStream fis = new FileInputStream(file)){

  49. int available = fis.available();

  50. long maxThreadNum = 3L;

  51. // 线程粗略开始位置

  52. long i = available / maxThreadNum;

  53. this.setRowList(new ArrayList<>());

  54. StaffSimpInfo staffSimpInfo = ((StaffSimpInfo)UserSessionHelper.getCurrentUserInfo().getData());

  55. String finalReportReceiver = getEmail(staffSimpInfo.getEmail(), reportImportReceiver);

  56. this.setReadColNum(Integer.parseInt(readColNum));

  57. this.setEncode(ReadFile.CHARSET_GB2312);

  58. //这里单独使用一个线程是为了当maxThreadNum大于1的时候,统一管理这些线程

  59. new Thread(()->{

  60. Thread preThread = null;

  61. FutureTask futureTask = null ;

  62. try {

  63. for (long j = 0; j < maxThreadNum; j++) {

  64. //计算精确开始位置

  65. long startNum = j == 0 ? 0 : readFile.getStartNum(file, i * j);

  66. long endNum = j + 1 < maxThreadNum ? readFile.getStartNum(file, i * (j + 1)) : -2L;

  67. //具体监听实现

  68. preThread = new ReadFileThread(this, startNum, endNum, file.getPath(), preThread);

  69. futureTask = new FutureTask(preThread, new Object());

  70. futureTask.run();

  71. }

  72. if(futureTask.get() != null) {

  73. EmailUtil.sendEmail(EmailUtil.REPORT_IMPORT_EMAIL_PREFIX, finalReportReceiver, "导入报表成功", "导入报表成功" ); //todo 等文案

  74. }

  75. } catch (Exception e){

  76. futureTask.cancel(true);

  77. try {

  78. EmailUtil.sendEmail(EmailUtil.REPORT_IMPORT_EMAIL_PREFIX, finalReportReceiver, "导入报表失败", e.getMessage());

  79. } catch (Exception e1){

  80. //ignore

  81. LOGGER.error("发送邮件失败", e1);

  82. }

  83. LOGGER.error("导入报表类型:"+importRequest.getReportType()+"失败", e);

  84. } finally {

  85. futureTask.cancel(true);

  86. }

  87. }).start();

  88. }

  89. }

  90. private String getEmail(String infoEmail, String reportImportReceiver){

  91. if(StringUtils.isEmpty(infoEmail)){

  92. return reportImportReceiver;

  93. }

  94. return infoEmail;

  95. }

  96. /**

  97. * 每批次调用导入接口

  98. * @param stringList

  99. * @throws Exception

  100. */

  101. @Override

  102. public void output(List stringList) throws Exception {

  103. ImportRequest importRequest = this.getOtherParams();

  104. List> dataList = stringList.stream()

  105. .map(x->Arrays.asList(x.split(ReadFile.SEPARATOR_COMMA)).stream().map(String::trim).collect(Collectors.toList()))

  106. .collect(Collectors.toList());

  107. LOGGER.info("上传数据:{}", dataList);

  108. importRequest.setDataList(dataList);

  109. // LOGGER.info("request对象:{}",importRequest, "request增加请求字段:{}", importRequest.data);

  110. ImportResponse importResponse = service.batchImport(importRequest);

  111. LOGGER.info("===========SUCESS_CODE======="+importResponse.getCode());

  112. //导入错误,输出错误信息

  113. if(!Constants.SUCESS_CODE.equals(importResponse.getCode())){

  114. LOGGER.error("导入报表类型:"+importRequest.getReportType()+"失败","返回码为:", importResponse.getCode() ,"返回信息:",importResponse.getMessage());

  115. throw new RuntimeException("导入报表类型:"+importRequest.getReportType()+"失败"+"返回码为:"+ importResponse.getCode() +"返回信息:"+importResponse.getMessage());

  116. }

  117. // if(importResponse.data != null && importResponse.data.get().get("batchImportFlag")!=null) {

  118. // LOGGER.info("eywa-service请求batchImportFlag不为空");

  119. // }

  120. importRequest.setData(importResponse.data);

  121. }

  122. }

注意:
第53行代码:
long maxThreadNum = 3L;
就是设置分批读取磁盘文件的线程数,我设置为3,大家不要设置太大,不然多个线程读取到内存,也会造成服务器内存溢出。

以上所有批次的批量读取并调用插入接口都成功发送邮件通知给导入人,任何一个批次失败直接发送失败邮件。 

数据库分批插入数据:

  1. /**

  2. * 批量插入非联机第三方导入账单

  3. * @param dataList

  4. */

  5. def insertNonOnlinePayment(dataList: List[NonOnlineSourceData]) : Unit = {

  6. if (dataList.nonEmpty) {

  7. CheckAccountDataSource.mysqlData.withConnection { conn =>

  8. val sql =

  9. s""" INSERT INTO t_pay_source_data

  10. (store_code,

  11. store_name,

  12. source_date,

  13. order_type,

  14. trade_type,

  15. third_party_payment_no,

  16. business_type,

  17. business_amount,

  18. trade_time,

  19. created_at,

  20. updated_at)

  21. VALUES (?,?,?,?,?,?,?,?,?,NOW(),NOW())"""

  22. conn.setAutoCommit(false)

  23. var stmt = conn.prepareStatement(sql)

  24. var i = 0

  25. dataList.foreach { x =>

  26. stmt.setString(1, x.storeCode)

  27. stmt.setString(2, x.storeName)

  28. stmt.setString(3, x.sourceDate)

  29. stmt.setInt(4, x.orderType)

  30. stmt.setInt(5, x.tradeType)

  31. stmt.setString(6, x.tradeNo)

  32. stmt.setInt(7, x.businessType)

  33. stmt.setBigDecimal(8, x.businessAmount.underlying())

  34. stmt.setString(9, x.tradeTime.getOrElse(null))

  35. stmt.addBatch()

  36. if ((i % 5000 == 0) && (i != 0)) { //分批提交

  37. stmt.executeBatch

  38. conn.commit

  39. conn.setAutoCommit(false)

  40. stmt = conn.prepareStatement(sql)

  41. }

  42. i += 1

  43. }

  44. stmt.executeBatch()

  45. conn.commit()

  46. }

  47. }

  48. }

 以上代码实现每5000 行提交一次批量插入,防止一次提较数据库的压力。

往期精彩

01 漫谈发版哪些事,好课程推荐

02 Linux的常用最危险的命令

03 精讲Spring Boot—入门+进阶+实例

04 优秀的Java程序员必须了解的GC哪些

05 互联网支付系统整体架构详解

关注我

每天进步一点点

喜欢!在看☟

你可能感兴趣的:(导入:Java实现大批量数据导入导出(100W以上))