ByteBuffer

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: ByteBuffer

ByteBuffer

基本使用

配置POM
 <dependencies>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.39.Final</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.guava/guava   工具类合集-->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic 日志-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
配置logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">

    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
    <property name="LOG_HOME" value="D:/log" />

    <!--控制台日志, 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度,%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <!--文件日志, 按照每天生成日志文件 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>
    <logger name="com.vmware.netty" level="DEBUG" />
    <!-- 日志输出级别 -->
    <root level="DEBUG">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE"/>
    </root>
</configuration>

测试NIO

@Slf4j
public class TestBuffer {
    public static void main(String[] args) {
        //获取channel 1.调用输入输出流的api间接获取  2.通过RandomAccessFile
        try (FileChannel channel = new FileInputStream("f.txt").getChannel()) {
            //准备缓冲区
            ByteBuffer byteBuffer=ByteBuffer.allocate(10);//申请一个10字节大小的缓冲区
            while (true) {
                //从channel中读取数据,会返回读取的字节数,如果channel中的数据读取完成则返回-1
                int len = channel.read(byteBuffer);
                log.debug("读取到的字节数:{}",len);
                if (len==-1){
                    break;
                }
                //设置byteBuffer为读模式
                byteBuffer.flip(); //flip:空翻
                while (byteBuffer.hasRemaining()) {//判断是否还有剩余未读数据
                    byte data = byteBuffer.get();//从buffer中读取一个字节的内容
                    log.debug("读取数据:{}", (char) data);
                }
                //切换bytebuffer为写模式
                byteBuffer.clear();
            }
        } catch (IOException e) {
        }
    }
}

ByteBuffer使用流程

1.向buffer写入数据,例如调用channel.read(buffer)

2.调用flip()切换到读模式(默认为写模式)

3.从buffer中读取数据,例如调用buffer.get()

4.调用clear()或compact()切换到写模式

5.重复1-4步骤

ByteBuffer结构

ByteBuffer有以下重要属性

  • capacity:容量
  • position:读写指针索引位置
  • limit:可操作区的边界值

一开始
aa75c146ab854e4388d6f0ce13bf6127.png

写模式下,position是写入位置,limit等于容量,下图为写入了4个字节后的状态

e91e584f903f403a82799620c1749428.png

flip动作发生后,position切换为读取位置,limit切换为读取限制

45ad205242fa4fd298b370807e0ec0d9.png

读取4个字节后,状态

e257d7d6043348d885eaa49ae2598b6f.png

clear动作发生后,状态

7281a1573ae44d8dbce6c3e82a97c59c.png

compact方法,是把未读完的部分向前压缩,然后切换为写模式

b357c778db70489291da54e99a9cd17b.png

ByteBuffer调试工具类

public class ByteBufferUtil {
    private static final char[] BYTE2CHAR = new char[256];
    private static final char[] HEXDUMP_TABLE = new char[256 * 4];
    private static final String[] HEXPADDING = new String[16];
    private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4];
    private static final String[] BYTE2HEX = new String[256];
    private static final String[] BYTEPADDING = new String[16];

    static {
        final char[] DIGITS = "0123456789abcdef".toCharArray();
        for (int i = 0; i < 256; i++) {
            HEXDUMP_TABLE[i << 1] = DIGITS[i >>> 4 & 0x0F];
            HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F];
        }

        int i;

        // Generate the lookup table for hex dump paddings
        for (i = 0; i < HEXPADDING.length; i++) {
            int padding = HEXPADDING.length - i;
            StringBuilder buf = new StringBuilder(padding * 3);
            for (int j = 0; j < padding; j++) {
                buf.append("   ");
            }
            HEXPADDING[i] = buf.toString();
        }

        // Generate the lookup table for the start-offset header in each row (up to 64KiB).
        for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i++) {
            StringBuilder buf = new StringBuilder(12);
            buf.append(StringUtil.NEWLINE);
            buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L));
            buf.setCharAt(buf.length() - 9, '|');
            buf.append('|');
            HEXDUMP_ROWPREFIXES[i] = buf.toString();
        }

        // Generate the lookup table for byte-to-hex-dump conversion
        for (i = 0; i < BYTE2HEX.length; i++) {
            BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
        }

        // Generate the lookup table for byte dump paddings
        for (i = 0; i < BYTEPADDING.length; i++) {
            int padding = BYTEPADDING.length - i;
            StringBuilder buf = new StringBuilder(padding);
            for (int j = 0; j < padding; j++) {
                buf.append(' ');
            }
            BYTEPADDING[i] = buf.toString();
        }

        // Generate the lookup table for byte-to-char conversion
        for (i = 0; i < BYTE2CHAR.length; i++) {
            if (i <= 0x1f || i >= 0x7f) {
                BYTE2CHAR[i] = '.';
            } else {
                BYTE2CHAR[i] = (char) i;
            }
        }
    }

    /**
     * 打印所有内容
     * @param buffer
     */
    public static void debugAll(ByteBuffer buffer) {
        int oldlimit = buffer.limit();
        buffer.limit(buffer.capacity());
        StringBuilder origin = new StringBuilder(256);
        appendPrettyHexDump(origin, buffer, 0, buffer.capacity());
        System.out.println("+--------+-------------------- all ------------------------+----------------+");
        System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), oldlimit);
        System.out.println(origin);
        buffer.limit(oldlimit);
    }

    /**
     * 打印可读取内容
     * @param buffer
     */
    public static void debugRead(ByteBuffer buffer) {
        StringBuilder builder = new StringBuilder(256);
        appendPrettyHexDump(builder, buffer, buffer.position(), buffer.limit() - buffer.position());
        System.out.println("+--------+-------------------- read -----------------------+----------------+");
        System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), buffer.limit());
        System.out.println(builder);
    }

    private static void appendPrettyHexDump(StringBuilder dump, ByteBuffer buf, int offset, int length) {
        if (MathUtil.isOutOfBounds(offset, length, buf.capacity())) {
            throw new IndexOutOfBoundsException(
                    "expected: " + "0 <= offset(" + offset + ") <= offset + length(" + length
                            + ") <= " + "buf.capacity(" + buf.capacity() + ')');
        }
        if (length == 0) {
            return;
        }
        dump.append(
                "         +-------------------------------------------------+" +
                        StringUtil.NEWLINE + "         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |" +
                        StringUtil.NEWLINE + "+--------+-------------------------------------------------+----------------+");

        final int startIndex = offset;
        final int fullRows = length >>> 4;
        final int remainder = length & 0xF;

        // Dump the rows which have 16 bytes.
        for (int row = 0; row < fullRows; row++) {
            int rowStartIndex = (row << 4) + startIndex;

            // Per-row prefix.
            appendHexDumpRowPrefix(dump, row, rowStartIndex);

            // Hex dump
            int rowEndIndex = rowStartIndex + 16;
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
            }
            dump.append(" |");

            // ASCII dump
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
            }
            dump.append('|');
        }

        // Dump the last row which has less than 16 bytes.
        if (remainder != 0) {
            int rowStartIndex = (fullRows << 4) + startIndex;
            appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);

            // Hex dump
            int rowEndIndex = rowStartIndex + remainder;
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
            }
            dump.append(HEXPADDING[remainder]);
            dump.append(" |");

            // Ascii dump
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
            }
            dump.append(BYTEPADDING[remainder]);
            dump.append('|');
        }

        dump.append(StringUtil.NEWLINE +
                "+--------+-------------------------------------------------+----------------+");
    }

    private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
        if (row < HEXDUMP_ROWPREFIXES.length) {
            dump.append(HEXDUMP_ROWPREFIXES[row]);
        } else {
            dump.append(StringUtil.NEWLINE);
            dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L));
            dump.setCharAt(dump.length() - 9, '|');
            dump.append('|');
        }
    }

    public static short getUnsignedByte(ByteBuffer buffer, int index) {
        return (short) (buffer.get(index) & 0xFF);
    }
}
调用调试工具类
public class TestByteBufferUtil {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        debugAll(buffer);
        buffer.put((byte) 0x61);
        debugAll(buffer);
        buffer.put(new byte[]{0x62, 0x63});
        debugAll(buffer);
        buffer.flip();//切换到读模式
        byte data = buffer.get();
        System.out.println((char) data);
        debugAll(buffer);
//        buffer.compact();//切换到写模式
//        debugAll(buffer);
//        buffer.put((byte)0x64);
//        debugAll(buffer);
        buffer.clear();
        debugAll(buffer);
    }
}

控制台

+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [10]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 00 00 00 00 00 00 00                   |abc.......      |
+--------+-------------------------------------------------+----------------+

ByteBuffer的常见方法

分配空间
  • 可以调用allocate方法为ByteBuffer分配空间,其他buffer类也有该方法

    ByteBuffer buffer = ByteBuffer.allocate(10);//java.nio.HeapByteBuffer 堆内存
    ByteBuffer buffer2 = ByteBuffer.allocateDirect(15);//java.nio.DirectByteBuffer 直接内存
    • java.nio.HeapByteBuffer: 堆内存,读写效率较低,受到GC的影响(数据会受复制算法影响,地址改变)
    • java.nio.DirectByteBuffer:直接内存,读写效率高(少一次拷贝),不会受GC影响,分配效率低
向buffer写入数据
  • 调用channel的read方法

    int read = channel.read(buffer);
  • 调用buffer的put方法

    buffer.put(new byte[]{0x17,0x18});
从buffer中读取数据
  • 调用channel的write方法

    int writeBytes = channel.write(buffer);
  • 调用buffer的get方法

    byte data = buffer.get();

get方法会让position读指针向后走,如果想要重复获取数据

  • 可以调用rewind方法将position重新置为0
  • 或者调用get(int i)方法获取索引i的内容,它不会移动读指针
其他方法
  • rewind:从头开始读
  • mark&reset:mark做一个标记,记录position的位置,reset是将position重置到mark的位置
public class TestBuffer3 {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        buffer.put(new byte[]{
                0x62,0x63,0x64
        });
        ByteBufferUtil.debugAll(buffer);
        buffer.flip();//切换读模式
        System.out.println((char) buffer.get());//b
        buffer.mark();//标记
        System.out.println((char) buffer.get());//c
        System.out.println((char) buffer.get());//d
        buffer.reset();//返回标记位
        System.out.println((char) buffer.get());//c
        System.out.println((char) buffer.get());//d
        buffer.rewind();//从头开始读
        System.out.println((char) buffer.get());//b
    }
}
ByteBuffer与字符串相互转换
  • ByteBuffer.warp(byte[] data):转ByteBuffer
  • StandardCharsets.UTF_8.encode(String s):转ByteBuffer
  • StandardCharsets.UTF_8.decode(ByteBuffer buffer):转ByteBuffer为字符串
public class ByteBufferRevString {
    public static void main(String[] args) {
        //字符串转ByteBuffer
        //1.通过默认方法
        byte[] bytes = "hello".getBytes();
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        byteBuffer.put(bytes);
        ByteBufferUtil.debugAll(byteBuffer);
        //2.通过CharSet工具类  自动转为读模式
        ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("hello");
        ByteBufferUtil.debugAll(buffer2);
        //通过bytebuffer的warp方法 自动转为读模式
        ByteBuffer buffer3 = ByteBuffer.wrap(bytes);
        ByteBufferUtil.debugAll(buffer3);

        //ByteBuffer转字符串
        byteBuffer.flip();//转读模式
        String string = StandardCharsets.UTF_8.decode(byteBuffer).toString();//hello
        System.out.println(string);
        String string1 = StandardCharsets.UTF_8.decode(buffer2).toString(); //hello
        System.out.println(string1);
    }
}

分散读与集中写

分散读

分散读就是要读取一部分数据,并且这部分数据最后要送入不同的buffer中,一种方法是先把他全部都读进来,然后分给不同的buffer,另一种就是使用一个channel,直接将数据送入不同的buffer中,需要注意的是,这些buffer的大小应该设置成它应该存入的数据的大小。channel中有read方法,参数可以是一个buffer,也可以是一个buffer数组,可以将需要读入的buffer组成一个buffer数组进行分散读

示例代码

public class TestScatterRead {
    public static void main(String[] args) {
        try (FileChannel channel = new RandomAccessFile("b.txt", "r").getChannel()) {
            ByteBuffer buffer1 = ByteBuffer.allocate(5);
            ByteBuffer buffer2 = ByteBuffer.allocate(5);
            ByteBuffer buffer3 = ByteBuffer.allocate(3);
            channel.read(new ByteBuffer[]{
                    buffer1,buffer2,buffer3
            });
            debugAll(buffer1);
            debugAll(buffer2);
            debugAll(buffer3);
        } catch (IOException e) {

        }
    }
}
集中写

集中写的思想是当有多个buffer想要写到一个文件中,同样有两种方式,一种是遍历每一个buffer,然后把各自的内容输出到文件中,第二种是集中写的方法,既使用一个channel,直接把所有buffer的内容放入文件中。channel中有方法write,同样的,可以给这个方法传入一组buffer,进行集中写

示例代码

public class TestGatheringWrite {
    public static void main(String[] args) {
        ByteBuffer buffer = StandardCharsets.UTF_8.encode("hello");
        ByteBuffer buffer1 = StandardCharsets.UTF_8.encode("world");
        ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("123");
        try (FileChannel channel = new RandomAccessFile("c.txt", "rw").getChannel()) {
            channel.write(new ByteBuffer[]{
                    buffer,buffer1,buffer2
            });
        } catch (IOException e) {
        }
    }
}

粘包和半包

什么是粘包和半包?

粘包是指数据在传输时,在一条消息中读取到了另一条消息的部分数据,这种现象称为粘包。

半包问题是指接收端只收到了部分数据,而非完整的数据就叫做半包。比如发送了一条消息是"ABC",而接收端却收到的是“AB”和"C"两条消息,这种情况叫半包

模拟粘包半包处理
public class TestByteBufferExam {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(32);
        buffer.put("Hello,world\nI'm zhangsan\nHo".getBytes());
        split(buffer);
        buffer.put("w are you?\n".getBytes());
        split(buffer);
    }

    //处理粘包和半包
    private static void split(ByteBuffer buffer) {
        buffer.flip();
        for (int index = 0; index < buffer.limit(); index++) {
            if (buffer.get(index) == '\n') {
                int length = index + 1 - buffer.position();
                ByteBuffer allocate = ByteBuffer.allocate(length);
                for (int i = 0; i < length; i++) {
                    allocate.put(buffer.get());
                }
                debugAll(allocate);
            }
        }
        buffer.compact();
    }
}
相关文章
2. ByteBuffer
2. ByteBuffer
35 0
|
3月前
|
存储
victoriaMetrics之byteBuffer
victoriaMetrics之byteBuffer
42 2
|
3月前
|
缓存 Java 索引
ByteBuffer 字节缓冲区
ByteBuffer 字节缓冲区
38 0
2.1 ByteBuffer 正确使用姿势
2.1 ByteBuffer 正确使用姿势
62 0
|
索引
2.3 ByteBuffer 常见方法
2.3 ByteBuffer 常见方法
65 0
|
存储
ByteBuffer 大小分配
ByteBuffer 大小分配
86 0
|
存储 Java 容器
|
存储 Java
NIO之Buffer解读(下)
NIO之Buffer解读(下)
|
存储 消息中间件 缓存
ByteBuffer总结
ByteBuffer总结
124 0
|
Java 测试技术 容器
NIO 下的 ByteBuffer简单学习
NIO 下的 ByteBuffer简单学习
117 0