簡體   English   中英

spring-kafka如何配置kafka消費者投票的頻率

[英]How to configure frequency for kafka consumer poll in spring-kafka

我正在嘗試在 Spring Boot 項目中使用 spring-kafka 從我的 kafka 讀取消息。 我正在使用 @KafkaListener 但問題是我的消費者總是在運行。 一旦我從控制台生成一條消息,它就會在我的應用程序中彈出。 我想定期進行輪詢。 我怎樣才能做到這一點?

@Service
public class KafkaReciever {

private static final Logger LOGGER =
        LoggerFactory.getLogger(KafkaReciever.class);

private CountDownLatch latch = new CountDownLatch(1);

public CountDownLatch getLatch() {
    return latch;
}

@KafkaListener(topics = "test")
public void receive(String payload) {
    LOGGER.info("received payload='{}'", payload);
    latch.countDown();
}

}

這是我的消費者配置:

@Bean
public Map<String, Object> consumerConfigs() {
    Map<String, Object> props = new HashMap<>();

    // list of host:port pairs used for establishing the initial connections to the Kafka cluster
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

    // allows a pool of processes to divide the work of consuming and processing records
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "foo1");

    // automatically reset the offset to the earliest offset
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    return props;
}

@Bean
public ConsumerFactory<String, String> consumerFactory() {
    return new DefaultKafkaConsumerFactory<>(consumerConfigs());
}

@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory =
            new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(consumerFactory());

    return factory;
}

這就是它的設計方式。 它是一個消息驅動的容器(與其他Spring消息傳遞技術抽象-RabbitMQ,JMS等保持一致)。

要僅按需獲取消息,您有兩種選擇:

  • 使用消費者工廠創建消費者,訂閱(或分配)主題/分區並調用poll()
  • 使用spring-integration-kafkaKafkaMessageSource並調用receive()

在這兩種情況下,如果您都使用kafka組管理,則需要注意max.poll.interval.ms以避免重新平衡。

您可以使用spring集成入站通道適配器來定期輪詢消息源。

從 2.3 版本開始,添加了一個名為idleBetweenPolls的新屬性。

從版本 2.3 開始,ContainerProperties 提供了一個 idleBetweenPolls 選項,讓偵聽器容器中的主循環在 KafkaConsumer.poll() 調用之間休眠。 從提供的選項和 max.poll.interval.ms 消費者配置與當前記錄批處理時間之間的差異中選擇實際睡眠間隔作為最小值。

這樣您就可以在消費者輪詢之間添加間隔。

來源: https : //docs.spring.io/spring-kafka/reference/html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM