[java] Java에서 Apache Avro를 이용한 데이터 직렬화 및 역직렬화

Apache Avro는 데이터 직렬화 및 역직렬화를 위한 오픈 소스 프레임워크입니다. Avro는 스키마를 이용하여 데이터를 직렬화하고, 스키마 정보를 포함한 파일 또는 메시지에 저장합니다. 이 기능은 다양한 언어와 플랫폼 간에 데이터를 효율적으로 교환하는 데 사용됩니다.

Avro의 기본 개념

Avro는 스키마 기반의 직렬화 시스템이며, 스키마는 데이터 구조를 정의하는 데 사용됩니다. 스키마는 JSON 형식으로 작성되며, 데이터의 필드 및 유형을 정의합니다. Avro는 동적이며 직관적인 데이터 모델을 제공하기 때문에 변화에 유연하게 대처할 수 있습니다.

데이터 직렬화 및 역직렬화

Avro를 사용하여 데이터를 직렬화하고 역직렬화하려면 다음 단계를 따를 수 있습니다.

1. 스키마 정의하기

Avro 스키마를 작성하여 직렬화 및 역직렬화할 데이터 구조를 정의합니다. 다음은 예시입니다.

{
  "type": "record",
  "name": "Person",
  "fields": [
    {
      "name": "name",
      "type": "string"
    },
    {
      "name": "age",
      "type": "int"
    }
  ]
}

2. 데이터 직렬화

Java 코드에서 Avro를 사용하여 데이터를 직렬화하는 방법은 다음과 같습니다.

import org.apache.avro.Schema;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.specific.SpecificDatumWriter;

public class AvroSerializationExample {

    public static void main(String[] args) throws Exception {
        // 스키마 정의
        Schema schema = new Schema.Parser().parse(new File("person.avsc"));
        
        // 데이터 객체 생성
        GenericRecord person = new GenericData.Record(schema);
        person.put("name", "John Doe");
        person.put("age", 30);
        
        // 데이터 직렬화
        DatumWriter<GenericRecord> writer = new SpecificDatumWriter<>(schema);
        Encoder encoder = EncoderFactory.get().binaryEncoder(outputStream, null);
        writer.write(person, encoder);
        encoder.flush();
        outputStream.close();
    }
}

3. 데이터 역직렬화

Java 코드에서 Avro를 사용하여 데이터를 역직렬화하는 방법은 다음과 같습니다.

import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;

public class AvroDeserializationExample {

    public static void main(String[] args) throws Exception {
        // 스키마 정의
        Schema schema = new Schema.Parser().parse(new File("person.avsc"));
        
        // 데이터 역직렬화
        DatumReader<GenericRecord> reader = new SpecificDatumReader<>(schema);
        Decoder decoder = DecoderFactory.get().binaryDecoder(inputStream, null);
        GenericRecord person = reader.read(null, decoder);
        inputStream.close();
        
        // 역직렬화된 데이터 사용
        String name = (String) person.get("name");
        int age = (int) person.get("age");
        
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

Avro를 사용하여 데이터를 직렬화 및 역직렬화하는 방법에 대해 알아보았습니다. Avro는 다른 언어 및 플랫폼과의 상호 운용성을 제공하며, 대용량 데이터 처리와 유연한 데이터 모델링에 유용한 도구입니다.

더 자세한 내용은 Apache Avro 공식 문서를 참조하시기 바랍니다.