IT자료실/Frameworks & Libraries

Netty Bytebuf

Ramda 2025. 2. 18. 13:51

Overview

네티를 공부하면서 ByteBuf가 핵심 클래스 중 하나로 생각된다. ByteBuf에 대해 더 알아보자.

What is Buffer?

ByteBuf를 알아보기 전에 Buffer란 무엇인지 먼저 알아보자.

Buffer는 중간 저장소의 역할이다. 데이터를 생성 할 때 버퍼에 넣어두고, 데이터를 사용하는 곳은 처리 가능한 속도로 항목을 가져온다. 데이터 처리 속도가 데이터 생성 속도보다 느려도, 공급된 데이터를 버퍼에 쌓아두기 때문에 끊김 없이 사용할 수 있다.

버퍼의 유용한 점이 이것이다. 데이터 생성 속도와 데이터 처리 속도가 다를 때 유용하다.

What is ByteBuf?

ByteBuf는 논리적인 바이트 컨테이너이다.

Java NIO는 바이트 컨테이너로 ByteBuffer를 제공하지만, 사용하기에 번거로운 단점이 있다.

이러한 번거로움을 해결하여 API를 사용하기 편하게 Netty에서 제공하는 것이 ByteBuf이다.

✋ Java ByteBuffer가 있지만, 사용하지 않는 이유는?

  • Netty에서 제공해주는 ByteBuf는 커널 버퍼에 직접 접근이 가능하다.
  • (Java NIO ByteBuffer는 접근 불가)

ByteBuf의 데이터를 보면 두 개의 포인터와 세 부분으로 나눠진다.

Discardable Bytes 부분은 읽은 데이터이며 이 데이터들은 버려질 수 있다.

Readable Bytes 부분의 데이터는 읽을 수 있는 데이터이다.

Writable Bytes 부분은 쓰기 가능한 영역이다.

  • Read Example
// Iterates the readable bytes of a buffer.
ByteBuf buffer = ...;
while (buffer.isReadable()) {
     System.out.println(buffer.readByte());
 }
  • Write Example
// Fills the writable bytes of a buffer with random integers.
ByteBuf buffer = ...;
while (buffer.maxWritableBytes() >= 4) {
    buffer.writeInt(random.nextInt());
}

Reference

https://www.baeldung.com/cs/buffer

 

ByteBuf (Netty API Reference (4.1.118.Final))

order @Deprecated public abstract ByteBuf order(ByteOrder endianness) Deprecated.  Returns a buffer with the specified endianness which shares the whole region, indexes, and marks of this buffer. Modifying the content, the indexes, or the marks of the

netty.io

 

'IT자료실 > Frameworks & Libraries' 카테고리의 다른 글

PF4J에서 Plugin을 상속 받는 이유  (1) 2025.02.18