avro反序列化

来源:互联网 发布:薪酬调查数据分析 编辑:程序博客网 时间:2021/10/19 08:10

avro反序列化的大概思路是:

  1. 维护一个DecoderFactory和BinaryDecoder,BinaryDecoder可以复用
  2. 维护一个GenericDatumReader和GenericRecord,GenericRecord可以复用
  3. 将byte[]传给decoderFactory
  4. 将decoderFactory传给genericDatumReader,将数据读到genericRecord里面
  5. 返回genericRecord
import org.apache.avro.Schema;import org.apache.avro.generic.GenericDatumReader;import org.apache.avro.generic.GenericRecord;import org.apache.avro.io.BinaryDecoder;import org.apache.avro.io.DecoderFactory;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.IOException;/** * Created by fhqplzj on 16-10-20 at 下午4:13. */public class AvroDeserialization {    Logger logger = LoggerFactory.getLogger(AvroDeserialization.class);    private GenericDatumReader<GenericRecord> genericDatumReader;    private GenericRecord genericRecord;    private DecoderFactory decoderFactory;    private BinaryDecoder binaryDecoder;    public AvroDeserialization(Schema schema) {        genericDatumReader = new GenericDatumReader<>(schema);        genericRecord = null;        decoderFactory = DecoderFactory.get();        binaryDecoder = null;    }    public GenericRecord fromBytes(byte[] bytes) {        binaryDecoder = decoderFactory.binaryDecoder(bytes, binaryDecoder);        try {            genericRecord = genericDatumReader.read(genericRecord, binaryDecoder);            return genericRecord;        } catch (IOException e) {            logger.error(e.getMessage());            return null;        }    }}


0 0