I try configure apache kafka in spring boot application. I read this documentation and follow the steps:
1) I add this lines to aplication.yaml
:
spring:
kafka:
bootstrap-servers: kafka_host:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringDeserializer
value-serializer: org.apache.kafka.common.serialization.ByteArraySerializer
2) I create new Topic:
@Bean
public NewTopic responseTopic() {
return new NewTopic("new-topic", 5, (short) 1);
}
And now I want use KafkaTemplate
:
private final KafkaTemplate<String, byte[]> kafkaTemplate;
public KafkaEventBus(KafkaTemplate<String, byte[]> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
But Intellij IDE highlights:
To fix this I need create bean:
@Bean
public KafkaTemplate<String, byte[]> myMessageKafkaTemplate() {
return new KafkaTemplate<>(greetingProducerFactory());
}
And pass to constructor propirties greetingProducerFactory()
:
@Bean
public ProducerFactory<String, byte[]> greetingProducerFactory() {
Map<String, Object> configProps = new HashMap<>();
configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka_hist4:9092");
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
return new DefaultKafkaProducerFactory<>(configProps);
}
But then what's the point of setting in application.yaml if I need create ProducerFactory manual?
I think you can safely ignore IDEA's warning; I have no problems wiring in Boot's template with different generic types...
and
By default
KafkaTemplate<Object, Object>
is created by Spring Boot inKafkaAutoConfiguration
class. Since Spring considers generic type information during dependency injection the default bean can't be autowired intoKafkaTemplate<String, byte[]>
.