Avro:使用新字段中的默认值保持向后功能,而不使用writer / old模式

时间:2017-10-15 05:43:25

标签: avro backwards-compatibility forward-compatibility

AVRO可以处理最常见的向前和向后兼容性。但是在使用更新的模式读取数据时,它以某种方式需要编写器模式。

说有一个旧架构:

{
  "type": "record",
  "name": "com.test.Contact",
  "fields": [
    {
      "name": "address",
      "type": "string"
    }
  ]
}

如果使用以下新架构来解码由旧架构编写的字节,则需要同时具有旧架构和新架构。

{
  "type": "record",
  "name": "com.test.Contact",
  "fields": [
    {
      "name": "address",
      "type": "string"
    },
    {
      "name": "phone",
      "type": ["null", "string"],
      "default": null
    }
  ]
}

要阅读的代码

    static void sede3() throws IOException {
        System.out.println("----------------------sede3---------------------");
        Schema.Parser parserNew = new Schema.Parser();
        Schema.Parser parserOld = new Schema.Parser();
        Schema addrSchemaNew = parserNew.parse(AppMainCore.class.getClassLoader()
                .getResourceAsStream("compatibility-new.schema.json"));
        Schema addrSchemaOld = parserOld.parse(AppMainCore.class.getClassLoader()
                .getResourceAsStream("compatibility-old.schema.json"));

        GenericRecord addressOld = new GenericData.Record(addrSchemaOld);
        addressOld.put("address", "ABCDEF");
        // Generate bytes using old schema.
        ByteArrayOutputStream bbos = new ByteArrayOutputStream();
        Encoder encoder = EncoderFactory.get().binaryEncoder(bbos, null);
        DatumWriter<GenericRecord> writer = new GenericDatumWriter<>(addrSchemaOld);
        writer.write(addressOld, encoder);
        encoder.flush();
        bbos.close();
        byte[] oldBytes = bbos.toByteArray();
        System.out.println(Hex.encodeHexString(oldBytes) + " is old record bytes");
        // Try to deserialize old bytes using new schema, with old schema's help
        DatumReader<GenericRecord> readerGood = new GenericDatumReader<>(addrSchemaOld, addrSchemaNew);
        Decoder decoderGood = DecoderFactory.get().binaryDecoder(oldBytes, null);
        GenericRecord goodAddress = readerGood.read(null, decoderGood);

        System.out.println(goodAddress + " is record from old bytes using new schema");
    }

我正在尝试使用新架构反序列化旧字节,没有旧架构的帮助。

像:

DatumReader<GenericRecord> readerGood = new GenericDatumReader<>(addrSchemaNew);

但不是

DatumReader<GenericRecord> readerGood = new GenericDatumReader<>(addrSchemaOld, addrSchemaNew);

Avro支持吗?

1 个答案:

答案 0 :(得分:0)

我认为不可能,请参阅此处的文档:https://avro.apache.org/docs/1.8.2/spec.html#Schema+Resolution。 Avro需要新旧架构来执行转换。