一.批量写入
Java写入大量数据到磁盘/数据库等其它第三方介质时,由于IO是比较耗费资源的操作,通常采用攒一批然后批量写入的模式
//通常构造一个缓存池,一个限制指标,可以是内存大小也可以是时间 ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); int size = 0; for (byte[] aByte : bytes) { //缓存池超过最大Size,进行一次刷新操作 if (size > SIZE_LIMIT) { doWrite(args); size = 0; byteBuffer.reset(); } size += aByte.length; try { byteBuffer.write(aByte); } catch (IOException e) { e.printStackTrace(); } } //如果循环结束,但byte数组不为空,则进行最后一次刷新操作 if (byteBuffer.size() != 0) { doWrite(args); byteBuffer.reset(); }
二.写入的重试
写入第三方介质时由于网络传输问题,可能出现数据丢失等问题,需要重传
基本的逻辑是只要捕捉到异常将isException置为True就进行重传,直到传输成功,将isException置为False
//是否需要重传的标记,我这里时捕捉到了异常,也可能来自其它的response boolean isException=false; try { writeData(args); } catch (Exception e) { log.error(e); isException=true; } while (isException) { try { writeData(args); isException=false; log.info("retry->success"); } catch (Exception e) { log.error("retry->failed",e); isException=true; } }