I went through the tutorial from baeldung. They mention there are two ways to create a schema.
- By writing the json representation and adding the maven plugin to produce the class
- By using the
SchemaBuilder, which they also mention is a better choice.
Unfortunately in the git example I only see the json way.
Lets say I have this Avro schema:
{
"type":"record",
"name":"TestFile",
"namespace":"com.example.kafka.data.ingestion.model",
"fields":[
{
"name":"date",
"type":"long"
},
{
"name":"counter",
"type":"int"
},
{
"name":"mc",
"type":"string"
}
]
}
By adding this plugin in my pom file:
<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>
and building with generate-sources a TestFile.java is created to the destination I said.
Then for sending to a kafka topic I can do the following:
TestFile test = TestFile.newBuilder()
.setDate(102928374747)
.setCounter(2)
.setMc("Some string")
.build();
kafkaTemplate.send(topicName, test);
The equivalent of creating the schema with SchemaBuilder would be:
Schema testFileSchema = SchemaBuilder .record("TestFile")
.namespace("com.example.kafka.data.ingestion.model")
.fields()
.requiredLong("date")
.requiredInt("counter")
.requiredString("mc")
.endRecord();
But how can I now generate the POJO and send my TestFile data to my kafka topic?