使用Spring-Kafka实现具有消息顺序保证的指数退避

14
我正在尝试实现一个基于Spring Boot的Kafka消费者,它具有非常强的消息传递保证,即使出现错误也是如此。
  • 必须按顺序处理来自分区的消息,
  • 如果消息处理失败,则应暂停对特定分区的消耗,
  • 应该使用退避重试处理,直到成功为止。
我们当前的实现满足这些要求:
@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
  ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
  factory.setConsumerFactory(consumerFactory());
  factory.setRetryTemplate(retryTemplate());

  final ContainerProperties containerProperties = factory.getContainerProperties();
  containerProperties.setAckMode(AckMode.MANUAL_IMMEDIATE);
  containerProperties.setErrorHandler(errorHandler());

  return factory;
}

@Bean
public RetryTemplate retryTemplate() {

  final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
  backOffPolicy.setInitialInterval(1000);
  backOffPolicy.setMultiplier(1.5);

  final RetryTemplate template = new RetryTemplate();
  template.setRetryPolicy(new AlwaysRetryPolicy());    
  template.setBackOffPolicy(backOffPolicy);

  return template;
}

@Bean
public ErrorHandler errorHandler() {
  return new SeekToCurrentErrorHandler();
}

然而,在这里,记录被消费者永久性地锁定。在某个时刻,处理时间将超过max.poll.interval.ms,服务器将重新分配分区给其他消费者,从而创建副本。

假设max.poll.interval.ms等于5分钟(默认值),且故障持续30分钟,则会导致消息被处理约6次。

另一种可能性是在N次重试后(例如3次尝试)将消息返回到队列中,使用SimpleRetryPolicy。然后,消息将被重新播放(感谢SeekToCurrentErrorHandler),并且处理将从头开始,最多进行5次尝试。这将导致形成一系列延迟。

10 secs -> 30 secs -> 90 secs -> 10 secs -> 30 secs -> 90 secs -> ...

比持续上升的数字更不受欢迎 :)

是否有第三种情况可以保持延迟形成一个升序序列,同时又不在上述示例中创建重复项?


但如果消费者数量等于主题数量,则该消费者变为空闲状态,Kafka 无法将其分配给其他消费者,因为所有其他消费者都在忙碌中(每个消费者一个线程)。 - Makoton
1个回答

8
可以使用有状态重试来实现-在这种情况下,每次重试后都会抛出异常,但是状态在重试状态对象中保持,因此该消息的下一次传递将使用下一个延迟等。需要在消息中添加某些内容(例如标题)以唯一标识每个消息。幸运的是,对于Kafka,主题、分区和偏移量提供了该状态的唯一键。但是,目前“RetryingMessageListenerAdapter”不支持有状态重试。您可以在侦听器容器工厂中禁用重试,并在侦听器中使用有状态的“RetryTemplate”,使用其中一个接受“RetryState”参数的“execute”方法。欢迎为框架添加支持有状态重试的GitHub问题; 欢迎贡献!-已发布拉取请求编辑 我刚刚编写了一个测试用例,以演示如何使用具有@KafkaListener的有状态恢复...
/*
 * Copyright 2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.kafka.annotation;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.listener.SeekToCurrentErrorHandler;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.kafka.test.rule.KafkaEmbedded;
import org.springframework.kafka.test.utils.KafkaTestUtils;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.retry.RetryState;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.support.DefaultRetryState;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author Gary Russell
 * @since 5.0
 *
 */
@RunWith(SpringRunner.class)
@DirtiesContext
public class StatefulRetryTests {

    private static final String DEFAULT_TEST_GROUP_ID = "statefulRetry";

    @ClassRule
    public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, 1, "sr1");

    @Autowired
    private Config config;

    @Autowired
    private KafkaTemplate<Integer, String> template;

    @Test
    public void testStatefulRetry() throws Exception {
        this.template.send("sr1", "foo");
        assertThat(this.config.listener1().latch1.await(10, TimeUnit.SECONDS)).isTrue();
        assertThat(this.config.listener1().latch2.await(10, TimeUnit.SECONDS)).isTrue();
        assertThat(this.config.listener1().result).isTrue();
    }

    @Configuration
    @EnableKafka
    public static class Config {

        @Bean
        public KafkaListenerContainerFactory<?> kafkaListenerContainerFactory() {
            ConcurrentKafkaListenerContainerFactory<Integer, String> factory =
                    new ConcurrentKafkaListenerContainerFactory<>();
            factory.setConsumerFactory(consumerFactory());
            factory.getContainerProperties().setErrorHandler(new SeekToCurrentErrorHandler());
            return factory;
        }

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

        @Bean
        public Map<String, Object> consumerConfigs() {
            Map<String, Object> consumerProps =
                    KafkaTestUtils.consumerProps(DEFAULT_TEST_GROUP_ID, "false", embeddedKafka);
            consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
            return consumerProps;
        }

        @Bean
        public KafkaTemplate<Integer, String> template() {
            KafkaTemplate<Integer, String> kafkaTemplate = new KafkaTemplate<>(producerFactory());
            return kafkaTemplate;
        }

        @Bean
        public ProducerFactory<Integer, String> producerFactory() {
            return new DefaultKafkaProducerFactory<>(producerConfigs());
        }

        @Bean
        public Map<String, Object> producerConfigs() {
            return KafkaTestUtils.producerProps(embeddedKafka);
        }

        @Bean
        public Listener listener1() {
            return new Listener();
        }

    }

    public static class Listener {

        private static final RetryTemplate retryTemplate = new RetryTemplate();

        private static final ConcurrentMap<String, RetryState> states = new ConcurrentHashMap<>();

        static {
            ExponentialBackOffPolicy backOff = new ExponentialBackOffPolicy();
            retryTemplate.setBackOffPolicy(backOff);
        }

        private final CountDownLatch latch1 = new CountDownLatch(3);

        private final CountDownLatch latch2 = new CountDownLatch(1);

        private volatile boolean result;

        @KafkaListener(topics = "sr1", groupId = "sr1")
        public void listen1(final String in, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
                @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
                @Header(KafkaHeaders.OFFSET) long offset) {
            String recordKey = topic + partition + offset;
            RetryState retryState = states.get(recordKey);
            if (retryState == null) {
                retryState = new DefaultRetryState(recordKey);
                states.put(recordKey, retryState);
            }
            this.result = retryTemplate.execute(c -> {

                // do your work here

                this.latch1.countDown();
                throw new RuntimeException("retry");
            }, c -> {
                latch2.countDown();
                return true;
            }, retryState);
            states.remove(recordKey);
        }

    }

}

并且

Seek to current after exception; nested exception is org.springframework.kafka.listener.ListenerExecutionFailedException: Listener method 'public void org.springframework.kafka.annotation.StatefulRetryTests$Listener.listen1(java.lang.String,java.lang.String,int,long)' threw exception; nested exception is java.lang.RuntimeException: retry

在每次投递尝试之后。

在这种情况下,我添加了一个恢复器来处理重试耗尽后的消息。您可以做其他事情,比如停止容器(但请在单独的线程上执行此操作,就像我们在ContainerStoppingErrorHandler中所做的那样)。


我添加了一个使用监听器中的有状态恢复的示例。 - Gary Russell
1
使用stateful-retry时,默认情况下状态保存在哪里?当在RetryTemplate上使用ExponentialBackoffPolicy时,我猜测必须检查消息的状态以查看下一个退避期间。请原谅我的无知,因为我是新手。 - Viraj
2
你应该提出一个新问题,而不是在旧问题上进行评论。使用有状态重试的原因是为了防止超过 max.poll.interval.ms 以避免重新平衡。SeekToCurrentErrorHandler 会重置偏移量,因此未处理的记录将在下一次轮询时重新获取;然后立即重新传递失败的记录,并暂停线程以进行下一次退避。因此,在Kafka中保留了一些状态(偏移量),而在内存中保留了一些状态(重试尝试、退避),但没有持久化。如果应用程序崩溃,则偏移量将被正确保留,但重试状态将从头开始。 - Gary Russell
@GaryRussell 谢谢。我正在寻找上述解决方案。您能否请解释一下锁存器的必要性,以及重试耗尽的意思是指指数退避将在30秒内重置吗? 还有,您在示例中提到的SeekToCurrentErrorHandler是指恢复程序吗? - Karthik Bharadwaj
1
这是一个旧答案,不要在这里提出新问题。自那时以来,情况已经发生了变化,STCEH现在已经添加了重试和退避功能,因此不再需要在侦听器级别重试。请参阅文档; 如果仍然有问题,请提出新问题。>现在,由于SeekToCurrentErrorHandler可以配置BackOff并且具有仅重试某些异常的能力(自版本2.3起),因此不再需要通过侦听器适配器重试配置使用有状态重试。... - Gary Russell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接