对于本机Java Kafka客户端,有一个名为enable.idempotence
的Kafka配置,我们可以将其设置为true
以启用幂等生成器。
但是,对于Spring Kafka,我在KafkaProperties
类中找不到类似的幂等属性。
所以我想知道,如果我在Spring Kafka配置文件中手动设置此属性是否生效,或者Spring会完全忽略Spring Kafka的此配置?
答案 0 :(得分:2)
有两种方法可以指定此属性
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());
}
}
答案 1 :(得分:1)
您正在尝试添加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
Yannick
答案 2 :(得分:0)
您可以在ProducerConfig
中找到它,因为它是生产者配置。为了启用此功能,您需要在producerConfigs中添加以下行:
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
producerProperties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);