【发布时间】:2019-06-09 07:25:35
【问题描述】:
我通过baeldung 完成了教程。他们提到有两种方法可以创建模式。
- 通过编写json表示并添加maven插件来生成类
- 通过使用
SchemaBuilder,他们还提到这是一个更好的选择。
不幸的是,在 git 示例中,我只看到了 json 方式。
假设我有这个 Avro 架构:
{
"type":"record",
"name":"TestFile",
"namespace":"com.example.kafka.data.ingestion.model",
"fields":[
{
"name":"date",
"type":"long"
},
{
"name":"counter",
"type":"int"
},
{
"name":"mc",
"type":"string"
}
]
}
通过在我的 pom 文件中添加这个插件:
<plugin>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>1.8.0</version>
<executions>
<execution>
<id>schemas</id>
<phase>generate-sources</phase>
<goals>
<goal>schema</goal>
<goal>protocol</goal>
<goal>idl-protocol</goal>
</goals>
<configuration>
<sourceDirectory>${project.basedir}/src/main/resources/</sourceDirectory>
<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
并使用 generate-sources 构建 TestFile.java 到我说的目的地。
然后,为了发送到 kafka 主题,我可以执行以下操作:
TestFile test = TestFile.newBuilder()
.setDate(102928374747)
.setCounter(2)
.setMc("Some string")
.build();
kafkaTemplate.send(topicName, test);
使用SchemaBuilder 创建架构的等价物是:
Schema testFileSchema = SchemaBuilder .record("TestFile")
.namespace("com.example.kafka.data.ingestion.model")
.fields()
.requiredLong("date")
.requiredInt("counter")
.requiredString("mc")
.endRecord();
但是我现在如何生成 POJO 并将我的 TestFile 数据发送到我的 kafka 主题?
【问题讨论】:
标签: java apache-kafka avro