如何序列化从Avro

时间:2016-08-16 10:22:22

标签: java serialization avro

我正在尝试为我的Avro生成的Java对象编写通用序列化程序。通过乞讨,借用和偷窃,我提出了以下方法:

public byte[] serialize(T data) {
    SpecificDatumWriter<T> writer = new SpecificDatumWriter<>(tClass);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
    try {
        writer.write(data, encoder);
        encoder.flush();
        ByteBuffer serialized = ByteBuffer.allocate(out.toByteArray().length);
        serialized.put(out.toByteArray());
        return serialized.array();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

我有两个问题:

  1. 架构是否包含在此字节数组中?如果我尝试用不同版本的tClass反序列化这个字节数组,它会没问题吗? (只要模式是向后兼容的)

  2. 如果这就是我要序列化Avro POJO的方式,那么如果我的Avro生成的POJO中使用了以下内容:

    public org.apache.avro.Schema getSchema() {
        return SCHEMA$;
    }
    
    private static final org.apache.avro.io.DatumWriter WRITER$ = new org.apache.avro.specific.SpecificDatumWriter(SCHEMA$);
    
    @Override
    public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException {
        WRITER$.write(this, SpecificData.getEncoder(out));
    }
    
    private static final org.apache.avro.io.DatumReader READER$ = new org.apache.avro.specific.SpecificDatumReader(SCHEMA$);
    
    @Override
    public void readExternal(java.io.ObjectInput in) throws java.io.IOException {
        READER$.read(this, SpecificData.getDecoder(in));
    }
    
  3. 我错过了什么吗?

0 个答案:

没有答案