Avro是一個數據序列化的項目,最開始是Hadoop的子項目之一,最後加入Apache成爲獨立的開元項目。Avro提供的功能類似於其他的編組系統,如Thrift、protobuf等。
Aro的主要不同之處在於:動態類型、無標記數據、不用手動分配字段ID。
另外,Avro支持兩種序列化編碼方式:二進制編碼和JSON編碼。
代碼如下:
package ares.remoting.framework.serialization.serializer.impl;
import ares.remoting.framework.serialization.serializer.ISerializer;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/**
* @author fuss created on 18/7/23.
* @version $Id$
*/
public class AvroSerializer implements ISerializer {
@Override
public <T> byte[] serialize(T obj) {
try {
DatumWriter userDatumWriter = new SpecificDatumWriter(obj.getClass());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BinaryEncoder binaryEncoder = EncoderFactory.get().directBinaryEncoder(outputStream, null);
userDatumWriter.write(obj, binaryEncoder);
return outputStream.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public <T> T deserialize(byte[] data, Class<T> clazz) {
try {
DatumReader userDatumReader = new SpecificDatumReader(clazz);
BinaryDecoder binaryDecoder = DecoderFactory.get().directBinaryDecoder(new ByteArrayInputStream(data), null);
return (T) userDatumReader.read(clazz.newInstance(), binaryDecoder);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
maven依賴配置,代碼如下:
<!-- avro -->
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro-ipc</artifactId>
<version>1.8.1</version>
</dependency>