简体   繁体   English

通用类型的 AVRO 模式 - Java

[英]AVRO schema for generic type - Java

I want to include traceId, and metadata for my Kafka message payload.我想为我的 Kafka 消息有效负载包含 traceId 和元数据。 so I have defined the below type for Kafka message payload.所以我为 Kafka 消息有效负载定义了以下类型。

public class KafkaMessage<T> {

    private String traceId;
    private Map<String, String> metaData = new HashMap<>();
    private T content;
}

then I have two type Dog and Cat.然后我有两种类型的狗和猫。 also I have created two Kafka message payload types two.我还创建了两种 Kafka 消息有效负载类型两种。

public class Dog {
    private int name;
}

public class DogKafkaMessage extends KafkaMessage<Dog>{

}

public class Car {
    private int numberOfWheels;
}

public class CarKafkaMessage extends KafkaMessage<Car> {

}

I want to represent these two types in Avro schema.我想在 Avro 模式中表示这两种类型。 is it possible to this way?有可能这样吗? if so please help me with this.如果是这样,请帮助我。

I can use JSON serializer/deserializer for Kafka message producer and consumer.我可以将 JSON 序列化器/反序列化器用于 Kafka 消息生产者和消费者。 but I look forward to using Avro.但我期待使用 Avro。

Thanks.谢谢。

Natively, Avro doesn't do generics or inheritance. Avro 本身不执行 generics 或 inheritance。 Jackson Avro library might help with this, but you may run into strange edge cases. Jackson Avro 库可能对此有所帮助,但您可能会遇到奇怪的边缘情况。

Instead, if you'd like to support more than only JVM implementations of Avro, you could define a schema that wraps bytes, and you'd have to deserialize events twice (outer and inner messages) where you can even mix and match data formats相反,如果您想支持的不仅仅是 Avro 的 JVM 实现,您可以定义一个包装字节的模式,并且您必须对事件进行两次反序列化(外部和内部消息),您甚至可以混合和匹配数据格式

record Event {
    string traceId;
    map<string> metadata;
    bytes content;
}

This is very similar to how CloudEvents spec works这与 CloudEvents 规范的工作方式非常相似

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM