【问题标题】:Spring Kafka Idempotence Producer configurationSpring Kafka 幂等生产者配置
【发布时间】:2019-11-30 09:57:56
【问题描述】:

对于原生 Java Kafka 客户端,有一个名为 enable.idempotence 的 Kafka 配置,我们可以将其设置为 true 以启用幂等生产者。

但是,对于 Spring Kafka,我在 KafkaProperties 类中找不到类似的幂等性。

所以我想知道,如果我在我的 Spring Kafka 配置文件中手动设置,这个属性是否会生效或者 Spring 会完全忽略 Spring Kafka 的这个配置?

【问题讨论】:

    标签: apache-kafka spring-kafka


    【解决方案1】:

    有两种方法可以指定这个属性

    application.properties您可以使用此属性来指定生产者的任何其他属性

    spring.kafka.producer.properties.*= # Additional producer-specific properties used to configure the client.
    

    如果您在生产者和消费者之间有任何额外的公共配置

    spring.kafka.properties.*= # Additional properties, common to producers and consumers, used to configure the client.
    

    通过代码您还可以覆盖和自定义配置

     @Bean
    public ProducerFactory<String, String> producerFactory() {
    
       Map<String, Object> configProps = new HashMap<>();
       configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,bootstrapAddress);
        configProps.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
        StringSerializer.class);
        configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, 
          StringSerializer.class);
        return new DefaultKafkaProducerFactory<>(configProps);
    }
    
    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
        }
     }
    

    【讨论】:

      【解决方案2】:

      您正在尝试添加 Spring KafkaProperties 未处理的功能,如果您查看文档,您可以执行以下操作:

      Only a subset of the properties supported by Kafka are available directly through the KafkaProperties class. 
      If you wish to configure the producer or consumer with additional properties that are not directly supported, use the following properties:
      
      spring.kafka.properties.prop.one=first
      spring.kafka.admin.properties.prop.two=second
      spring.kafka.consumer.properties.prop.three=third
      spring.kafka.producer.properties.prop.four=fourth
      spring.kafka.streams.properties.prop.five=fifth
      

      https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-messaging.html#boot-features-kafka-extra-props

      亚尼克

      【讨论】:

        【解决方案3】:

        您可以使用ProducerConfig 找到它,因为它是生产者配置。为了启用此功能,您需要在 producerConfigs 中添加以下行:

          Properties producerProperties = new Properties();
          producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
          producerProperties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-05-10
          • 2020-02-09
          • 1970-01-01
          • 1970-01-01
          • 2016-04-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多