Search code examples
apache-kafkaschemaavroconfluent-platformproducer

Fetching avro schema for producer from schema registry in code


Confluent provides following example:

String key = "key1";
String userSchema = "{\"type\":\"record\"," +
                "\"name\":\"myrecord\"," +
                "\"fields\":[{\"name\":\"f1\",\"type\":\"string\"}]}";
Schema.Parser parser = new Schema.Parser();
Schema schema = parser.parse(userSchema);
GenericRecord avroRecord = new GenericData.Record(schema);
avroRecord.put("f1", "value1");
ProducerRecord<Object, Object> record = new ProducerRecord<>("topic1", key, avroRecord);
try {
  producer.send(record);
} catch(SerializationException e) {
  // may need to do something with it
}

Is there any way to fetch userSchema for producer directly from schema registry (if already exists), instead of hard-coding it?


Solution

  • You can use the Maven plugin to download the schema.

    There is also the REST API if you literally want to fetch the schema at runtime.