spring boot中创建KafkaTemplate的正确方法

ip6*_*696 11 java spring apache-kafka spring-boot spring-kafka

我尝试在Spring Boot 应用程序中配置apache kafka。我阅读了此文档并按照以下步骤操作:

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
Run Code Online (Sandbox Code Playgroud)

2)我创建新主题:

    @Bean
    public NewTopic responseTopic() {
        return new NewTopic("new-topic", 5, (short) 1);
    }
Run Code Online (Sandbox Code Playgroud)

现在我想使用KafkaTemplate

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

public KafkaEventBus(KafkaTemplate<String, byte[]> kafkaTemplate) {
    this.kafkaTemplate = kafkaTemplate;
}
Run Code Online (Sandbox Code Playgroud)

但 Intellij IDE 强调:

在此处输入图片说明

为了解决这个问题,我需要创建 bean:

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

并传递给构造函数属性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);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我需要创建 ProducerFactory 手册,那么在application.yam l中设置的意义何在?

Gar*_*ell 6

我认为您可以放心地忽略 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

they are the same
Run Code Online (Sandbox Code Playgroud)


Kar*_*cki 5

默认情况下由 Spring Boot 在classKafkaTemplate<Object, Object>中创建。由于 Spring 在依赖注入期间考虑通用类型信息,因此默认 bean 无法自动装配到.KafkaAutoConfigurationKafkaTemplate<String, byte[]>