在春季启动中创建KafkaTemplate的正确方法

时间:2019-03-21 12:11:28

标签: java spring spring-boot apache-kafka spring-kafka

我尝试在 spring boot 应用程序中配置 apache kafka 。我阅读了此documentation ,并按照以下步骤操作:

1)我将此行添加到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)我创建了新主题:

    @Bean
    public NewTopic responseTopic() {
        return new NewTopic("new-topic", 5, (short) 1);
    }

现在我要使用KafkaTemplate

private final KafkaTemplate<String, byte[]> kafkaTemplate;

public KafkaEventBus(KafkaTemplate<String, byte[]> kafkaTemplate) {
    this.kafkaTemplate = kafkaTemplate;
}

但是Intellij IDE突出显示:

enter image description here

要解决此问题,我需要创建bean:

@Bean
public KafkaTemplate<String, byte[]> myMessageKafkaTemplate() {
    return new KafkaTemplate<>(greetingProducerFactory());
}

并传递给构造函数属性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);
}

但是如果我需要创建ProducerFactory手册,那么在 application.yam l中进行设置有什么意义呢?

3 个答案:

答案 0 :(得分:2)

我认为您可以放心忽略IDEA的警告;我在使用不同的通用类型的Boot模板中进行接线没有问题...

@SpringBootApplication
public class So55280173Application {

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

    @Bean
    public ApplicationRunner runner(KafkaTemplate<String, String> template, Foo foo) {
        return args -> {
            template.send("so55280173", "foo");
            if (foo.template == template) {
                System.out.println("they are the same");
            }
        };
    }

    @Bean
    public NewTopic topic() {
        return new NewTopic("so55280173", 1, (short) 1);
    }

}

@Component
class Foo {

    final KafkaTemplate<String, String> template;

    @Autowired
    Foo(KafkaTemplate<String, String> template) {
        this.template = template;
    }

}

they are the same

答案 1 :(得分:0)

默认情况下,KafkaTemplate<Object, Object>由Spring Boot在KafkaAutoConfiguration class中创建。由于Spring在依赖项注入期间会考虑泛型类型信息,因此无法将默认bean自动装配到KafkaTemplate<String, byte[]>中。

答案 2 :(得分:0)

最初,我遇到了同样的问题,但是当我执行该操作时,没有出现任何错误,并且工作正常。

忽略 Intellij IDEA的警告,这可能是IDEA找出自动装配组件的错误。

相关问题