java - spring boot中创建KafkaTemplate的正确方法

标签 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.yaml 中设置有什么意义呢?

最佳答案

我认为您可以安全地忽略 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

关于java - spring boot中创建KafkaTemplate的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55280173/

相关文章:

java - JBoss部署后调用方法

java - NoClassDefFoundError 在协议(protocol)上需要其命名空间时

java - 构建spring框架源码遇到错误

java - 使用不同的 Spring 属性进行集成测试

java - 如何在非 "RequestMapping"方法中进行依赖注入(inject)

java - 检查 onResume() 方法的原因

java - 如何在 Apache POI 中创建 XSFTable

java - 当我从 @RestControler 返回对象时,如何在 json 中保留 map 键顺序

spring-boot - Spring boot Flyway Jooq Code gen maven插件顺序

spring-boot - Vaadin 流程应用程序无法与 Spring Boot 2.6.0 配合使用