'Kafka headers with type of string

Kafka headers values are type of byte array and for some reason I need to use string type of value for one of the header. Is it possible to manage it somehow instead of handling it in the listener ?



Solution 1:[1]

The framework takes care of the conversion automically:

@SpringBootApplication
public class So71941853Application {

    public static void main(String[] args) {
        SpringApplication.run(So71941853Application.class, args);
    }

    @KafkaListener(id = "so71941853", topics = "so71941853")
    void listen(String in, @Header("hdr") String foo) {
        System.out.println(in + " - " + foo);
    }

    @Bean
    public NewTopic topic() {
        return TopicBuilder.name("so71941853").partitions(1).replicas(1).build();
    }

    @Bean
    ApplicationRunner runner(KafkaTemplate<String, String> template) {
        template.setDefaultTopic("so71941853");
        return args -> {
            template.send(new GenericMessage<>("foo", Collections.singletonMap("hdr", "bar".getBytes())));
        };
    }

}
foo - bar

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 Gary Russell