zoukankan      html  css  js  c++  java
  • Java写入的常用技巧

    一.批量写入

    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;
                }
            }
  • 相关阅读:
    idea 连接 hive
    css img自适应
    测试视频文件
    ubuntu不显示ipv4地址的解决办法
    nginx path捕获
    union all两个结果集报ORA-12704: character set mismatch错误
    润乾报表试用指南
    报表工具对比之润乾报表与锐浪报表对比
    项目微管理36
    docker远程调用
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/11555730.html
Copyright © 2011-2022 走看看