user16592652
user16592652

Reputation:

Spring boot 2x + Kafka API produce JSON object instead of String/Generic

How code looks at the moment: (template)

@Configuration
public class KafkaConfiguration {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
        return props;
    }

    @Bean
    public ProducerFactory<String, Object> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public KafkaTemplate<String, Object> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }

    public void send(String topicName, Object body) {
        kafkaTemplate.send(topic, body);
    }
    //In send method i am sending simple json in string format: {"name":"Leo", "age": "51"}
    //Would be better if i change object to JSON type and which type should   
    // i provide?
}

In which type should i send this string in best way? Should i use something like JSONObject? Or should i use ObjectMapper to get json from this string?

Upvotes: 0

Views: 1515

Answers (1)

vaibhavsahu
vaibhavsahu

Reputation: 682

it is always a better approach to use JSON payload for producing messages.

you can write a custom method to serialize String to JSON

private final static ObjectWriter writer = new ObjectMapper().writerFor(TopicRecord.class);
private String serialize(TopicRecord topicRecord) {
    try {
      return writer.writeValueAsString(topicRecord);
    } catch (JsonProcessingException e) {
      throw new RuntimeException("Unable to serialize topic record to json", e);
    }
  }

Upvotes: 0

Related Questions