Kafka Consumer - 在recover方法中获取侦听器接收的参数

时间:2017-10-05 19:19:51

标签: spring spring-boot kafka-consumer-api kafka-producer-api spring-kafka

我正在建立一个春天卡夫卡消费者。我已经设置了重试机制。重试耗尽后,我想将失败的消息推送到死信主题。

listen方法具有以下参数

public void listen(@Payload Map<String, Object> conciseMap,
        @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
        Acknowledgment ack) throws JsonProcessingException {

作为recover方法的一部分,我想获取作为输入传递给侦听器映射的conciseMap或我的主题接收的原始消息。有办法吗?

@Bean
public ConcurrentKafkaListenerContainerFactory<String, Map<String, Object>> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, Map<String, Object>> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConcurrency(conncurrency);
    factory.setConsumerFactory(consumerFactory());
    factory.setRetryTemplate(retryTemplate());
    factory.setRecoveryCallback(new RecoveryCallback<Object>() {
        @Override
        public Object recover(RetryContext context) throws Exception {
            // TODO Auto-generated method stub
            logger.debug(" In recovery callback method !!");
            ((Acknowledgment)context.getAttribute(RetryingMessageListenerAdapter.CONTEXT_ACKNOWLEDGMENT)).acknowledge();

            return null;
        }
    });
    factory.getContainerProperties().setAckMode(AckMode.MANUAL);
    return factory;
}

        factory.getContainerProperties().setAckMode(AckMode.MANUAL);
        return factory;
    }

    /*
     * Retry template.
     */

    protected RetryPolicy retryPolicy() {
        SimpleRetryPolicy policy = new SimpleRetryPolicy(maxRetryAttempts, retryableExceptions);
        return policy;
    }

    protected BackOffPolicy backOffPolicy() {
        ExponentialBackOffPolicy policy = new ExponentialBackOffPolicy();
        policy.setInitialInterval(initialRetryInterval);
        policy.setMultiplier(retryMultiplier);
        return policy;
    }

    protected RetryTemplate retryTemplate() {
       RetryTemplate template = new RetryTemplate();
       template.setRetryPolicy(retryPolicy());
       template.setBackOffPolicy(backOffPolicy());
       return template;
    }
}

1 个答案:

答案 0 :(得分:1)

您无法在conciseMap RecoveryCallback中获得转换RetryContext,但您可以检索ConsumerRecord来自(ConsumerRecord) context.getAttribute(RetryingMessageListenerAdapter.CONTEXT_RECORD) 的{​​{1}}转换前的主题:

Bad2.addx[0] = "dan"