Spring Boot 如何使用Kafka的Acknowledgement.acknowledge()方法进行手动提交

ubof19bj  于 2022-12-13  发布在  Spring
关注(0)|答案(3)|浏览(304)

我是第一次使用Spring Kafka,我不能使用Acknowledgement.acknowledge()方法在我的消费者代码中进行手动提交,如这里提到的https://docs.spring.io/spring-kafka/reference/html/_reference.html#committing-offsets。我的是spring-boot应用程序。如果我不使用手动提交过程,我的代码工作正常。但当我使用Acknowledgement.acknowledge()对于手动提交,它显示与bean相关的错误。另外,如果我没有正确使用手动提交,请建议我正确的方法。
错误消息:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field ack in Receiver required a bean of type 'org.springframework.kafka.support.Acknowledgment' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.kafka.support.Acknowledgment' in your configuration.

我在谷歌上搜索了这个错误,我发现我需要添加 @Component ,但这已经在我的消费者代码中了。
我的消费者代码如下所示:Receiver.java

import java.util.concurrent.CountDownLatch;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

@Component
public class Receiver {

    @Autowired
    public Acknowledgment ack;

    private CountDownLatch latch = new CountDownLatch(1);

    @KafkaListener(topics = "${kafka.topic.TestTopic}")
    public void receive(ConsumerRecord<?, ?> consumerRecord){
            System.out.println(consumerRecord.value());
            latch.countDown();
            ack.acknowledge();
    }
}

我的生产者代码如下所示:Sender.java

import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

@Component
public class Sender {

    @Autowired
    private KafkaTemplate<String, Map<String, Object>> kafkaTemplate;

    public void send(Map<String, Object> map){
            kafkaTemplate.send("TestTopic", map);

    }

}

编辑1:

我的新消费者代码如下所示:Receiver.java

import java.util.concurrent.CountDownLatch;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

@Component
public class Receiver {

    private CountDownLatch latch = new CountDownLatch(1);

    @KafkaListener(topics = "${kafka.topic.TestTopic}", containerFactory = "kafkaManualAckListenerContainerFactory")
    public void receive(ConsumerRecord<?, ?> consumerRecord, Acknowledgment ack){
            System.out.println(consumerRecord.value());
            latch.countDown();
            ack.acknowledge();
    }
}

我还更改了配置类:

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;

@Configuration
@EnableKafka
public class ReceiverConfig {

    @Value("${kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Value("${spring.kafka.consumer.group-id}")
    private String consumerGroupId;

    @Bean
    public Map<String, Object> consumerConfigs() throws SendGridException {
            Map<String, Object> props = new HashMap<>();
            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);
            props.put(ConsumerConfig.GROUP_ID_CONFIG, consumerGroupId);
            return props;

    }

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

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

        return factory;
    }*/

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaManualAckListenerContainerFactory(){
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        return factory;
    }

    @Bean
    public Receiver receiver() {
        return new Receiver();
    }
}

在将containerFactory =“kafkaManualAckListenerContainerFactory”添加到我的receive()方法后,我收到以下错误。

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of method kafkaListenerContainerFactory in org.springframework.boot.autoconfigure.kafka.KafkaAnnotationDrivenConfiguration required a bean of type 'org.springframework.kafka.core.ConsumerFactory' that could not be found.
    - Bean method 'kafkaConsumerFactory' in 'KafkaAutoConfiguration' not loaded because @ConditionalOnMissingBean (types: org.springframework.kafka.core.ConsumerFactory; SearchStrategy: all) found bean 'consumerFactory'

Action:

Consider revisiting the conditions above or defining a bean of type 'org.springframework.kafka.core.ConsumerFactory' in your configuration.
vd8tlhqk

vd8tlhqk1#

对于那些仍在寻找手动确认相关错误解决方案的用户,您不需要指定containerFactory =“kafkaManualAckListenerContainerFactory”,而只需添加:

factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);

在返回工厂对象之前,将其添加到接收器配置中。
然后您还需要:

props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

消费者配置 prop 。
因此,最终您的侦听器方法可以简单地如下所示:

@KafkaListener(topics = "${spring.kafka.topic}")
    private void listen(@Payload String payload, Acknowledgment acknowledgment) {
        //Whatever code you want to do with the payload
        acknowledgement.acknowledge(); //or even pass the acknowledgment to a different method and acknowledge even later
    }
l0oc07j2

l0oc07j22#

您确实应该遵循文档:
当使用说明书AckMode时,监听器也可以提供Acknowledgment;此示例还显示了如何使用不同的容器工厂。

@KafkaListener(id = "baz", topics = "myTopic",
          containerFactory = "kafkaManualAckListenerContainerFactory")
public void listen(String data, Acknowledgment ack) {
    ...
    ack.acknowledge();
}

实际上没有任何地方指出Acknowledgment是一个bean。因此,适当地更改您的receive()@KafkaListener方法签名,并删除可疑的Acknowledgment bean的@Autowired-它只是不存在,因为该对象是每个接收到的消息的一部分(头部)。

a0x5cqrl

a0x5cqrl3#

那些正在使用spring Boot 的应用程序,简单的添加到你的应用程序下面.yml(或环境特定的文件)。

spring:
  kafka:
    listener:
      ack-mode: manual

以上更改将使Acknowledgment ack参数在内部可用
receive(ConsumerRecord<?, ?> consumerRecord, Acknowledgment ack)方法自动执行。

相关问题