'Kafka - how to send complex value?

I have this method

  @PutMapping("/{id}/increase")
    @KafkaListener(
            id = "increaseBalanceId",
            topics = "increaseBalanceTopic"
    )
    public ResponseEntity<Long> increaseBalance(
            @PathVariable final Integer id,
            @RequestParam final Long valueForUpdated
    ) {
        return ResponseEntity
                .ok()
                .body(balanceService.increaseBalance(id, valueForUpdated));
    }

I try to send message like this:

@Override
    public Long decreaseBalance(final Integer id, final Long value) {
        final String msg = String.format(
                "{\"id\": %d, \"valueForUpdated\": \"%d\"}",
                id,
                value
        );
        final ProducerRecord<String, Object> producerRecord = new ProducerRecord<>(
                decreaseBalanceTopic, msg
        );
        kafkaTemplate.send(producerRecord);
        return null;
    }

but its not working. How to send multiple message in kafka?



Solution 1:[1]

send multiple message

Call kafkaTemaplate.send multiple times.

send complex value

You can define a producer serializer class to serialize any POJO. Spring-Kafka has a built-in JSONSerializer

However, I'd recommend you put the ID as the key of the record (IntegetSerializer) and the value and the Kafka record value (LongSerializer)

final ProducerRecord<Integer, Long> producerRecord = new ProducerRecord<>(decreaseBalanceTopic, id, value);

kafkaTemplate.send(producerRecord);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 OneCricketeer