【问题标题】:ExecutionException:Due to: org.springframework.kafka.requestreply.KafkaReplyTimeoutException: Reply timed out using ReplyingKafkaTemplateExecutionException:由于:org.springframework.kafka.requestreply.KafkaReplyTimeoutException:使用ReplyingKafkaTemplate回复超时
【发布时间】:2022-09-28 03:13:34
【问题描述】:

我正在使用 kafka 将异步和同步消息发布到代理。一个侦听器将侦听主题并响应同步和异步调用。我对两个模板使用相同的请求主题。. 当使用 fire and forget(Async) 时,我看不到任何问题,因为侦听器会从主题中随机收听消息。使用同步调用时,我遇到超时异常。

  1. 我需要为不同的模板维护多个监听器吗?
  2. 如果同步和异步操作的主题相同,会有什么问题吗?

    KafkaConfig.java

    //Template for synchornous call

    @Bean 
    public ReplyingKafkaTemplate<String, Model, Model> replyingKafkaTemplate (
        ProducerFactory<String, Model> pf,
        ConcurrentMessageListenerContainer<String, Model> repliesContainer)
    {
        ReplyingKafkaTemplate<String, Model, Model> replyTemplate =
            new ReplyingKafkaTemplate<>(pf, repliesContainer);
        replyTemplate.setSharedReplyTopic(true);
        return replyTemplate;
    }
    
    @Bean //register ConcurrentMessageListenerContainer bean
    public ConcurrentMessageListenerContainer<String, Model> repliesContainer (
        ConcurrentKafkaListenerContainerFactory<String, Model> containerFactory)
    {
        ConcurrentMessageListenerContainer<String, Model> repliesContainer =
            containerFactory.createContainer(\"responseTopic\");
        repliesContainer.getContainerProperties().setGroupId(UUID.randomUUID().toString());
        repliesContainer.setAutoStartup(false);
        return repliesContainer;
    }
    

    //Template for asynchronous call

    @Bean
    
    @Qualifier(\"kafkaTemplate\")
    public KafkaTemplate<String, Model> kafkaTemplate (
        ProducerFactory<String, Model> pf,
        ConcurrentKafkaListenerContainerFactory<String, Model> factory)
    {
        KafkaTemplate<String, Model> kafkaTemplate = new KafkaTemplate<>(pf);
        factory.setReplyTemplate(kafkaTemplate);
        return kafkaTemplate;
    }
    

    这里是服务类

    @Service
    public class KafkaService
    {
        @Autowired
        private ReplyingKafkaTemplate<String, Model, Model> replyingKafkaTemplate;
        @Autowired
        private KafkaTemplate<String, Model> kafkaTemplate;
        @Autowired
        private KafkaConfig config;
        public Object sendAndReceive (Model model)
        {
    
            ProducerRecord<String, Model> producerRecord =
                new ProducerRecord(\"requestTopic\", model);
            producerRecord.headers()
                .add(
                    new RecordHeader(KafkaHeaders.REPLY_TOPIC, \"replyTopic\"));
            RequestReplyFuture<String, Model, Model> replyFuture =
                replyingKafkaTemplate.sendAndReceive(producerRecord, Duration.ofSeconds(timeout));
            ConsumerRecord<String, Model> consumerRecord =
                replyFuture.get(timeout, TimeUnit.SECONDS);
            return consumerRecord.value();
    
        }
        public ResponseEntity<Object> send (final Model model)
        {
    
            final ProducerRecord<String, Model> producerRecord =
                new ProducerRecord(\"requestTopic\", model);
            final ListenableFuture<SendResult<String, Model>> future =
                kafkaTemplate.send(producerRecord);
            final SendResult<String, Model> sendResult = future.get(timeout, TimeUnit.SECONDS);
            return new ResponseEntity<>(sendResult, HttpStatus.ACCEPTED);
        }
    
    }
    

    这是侦听器类。

    @Slf4j
    @Service
    public class MessageListener
    {
        @KafkaListener(groupId = \"${group.id}\", topics = \"requestTopic\", errorHandler = \"customKafkaListenerErrorHandler\",containerFactory = \"customKafkaListenerContainerFactory\")
        @SendTo
        public Model consumer (Model model)
        {
            switch (model.getType()) {
            case \"async\":
                System.out.println(\"Async messages are retrieved\");
            case \"sync\":
                System.out.println(\"Sync messages are retrieved\");
                return model;
            }
            return model;
        }
    
        @Bean
        public ConcurrentKafkaListenerContainerFactory<?, ?> customKafkaListenerContainerFactory(
            ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
            ConsumerFactory<Object, Object> kafkaConsumerFactory)
        {
            ConcurrentKafkaListenerContainerFactory<Object, Object>
            concurrentKafkaListenerContainerFactory =
            new ConcurrentKafkaListenerContainerFactory<>();
            concurrentKafkaListenerContainerFactory.
            setConsumerFactory(kafkaConsumerFactory);
           concurrentKafkaListenerContainerFactory.getContainerProperties()
           .setAckMode(ContainerProperties.AckMode.RECORD);
           concurrentKafkaListenerContainerFactory.
           setCommonErrorHandler(errorHandler());
           configurer.configure(concurrentKafkaListenerContainerFactory, kafkaConsumerFactory);
        concurrentKafkaListenerContainerFactory.setReplyTemplate(kafkaTemplate);
        return concurrentKafkaListenerContainerFactory;
        }
    }
    

    应用程序属性

    spring.kafka.consumer.enable-auto-commit=false spring.kafka.consumer.auto-offset-reset=最早

  • @Gary Russell,你能检查一下吗?
  • 您应该显示每种操作类型之一的调试日志(客户端和服务器端)。

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


【解决方案1】:

这完全符合我的预期......

@SpringBootApplication
public class So73657031Application {

    public static void main(String[] args) {
        SpringApplication.run(So73657031Application.class, args);
    }

    @Bean
    ReplyingKafkaTemplate<String, String, String> rkt(ProducerFactory<String, String> pf,
            ConcurrentKafkaListenerContainerFactory<String, String> factory,
            KafkaTemplate<String, String> template) {

        factory.setReplyTemplate(template);
        ConcurrentMessageListenerContainer<String, String> container = factory.createContainer("so73657031-replies");
        container.getContainerProperties().setGroupId("so73657031-replies");
        return new ReplyingKafkaTemplate<>(pf, container);
    }

    @Bean
    KafkaTemplate<String, String> template(ProducerFactory<String, String> pf) {
        return new KafkaTemplate<>(pf);
    }

    @Bean
    NewTopic topic1() {
        return TopicBuilder.name("so73657031").partitions(1).replicas(1).build();
    }

    @Bean
    NewTopic topic2() {
        return TopicBuilder.name("so73657031-replies").partitions(1).replicas(1).build();
    }

    @Bean
    public ApplicationRunner runner(ReplyingKafkaTemplate<String, String, String> rTemplate,
            KafkaTemplate<String, String> template) {

        return args -> {
            RequestReplyFuture<String, String, String> future =
                    rTemplate.sendAndReceive(new ProducerRecord<String, String>("so73657031", 0, null, "test"),
                            Duration.ofSeconds(30));
            System.out.println(future.getSendFuture().get(10, TimeUnit.SECONDS).getRecordMetadata());
            System.out.println(future.get(30, TimeUnit.SECONDS).value());
            ListenableFuture<SendResult<String, String>> future2 = template.send("so73657031", "oneWay");
            System.out.println(future2.get(10, TimeUnit.SECONDS).getRecordMetadata());
        };
    }

}

@Component
class Listener {


    @KafkaListener(id = "so73657031", topics = "so73657031")
    @SendTo
    String listen(String in) {
        System.out.println(in);
        return in.toUpperCase();
    }

}
logging.level.root=warn
logging.level.org.springframework.kafka.listener.adapter=debug
so73657031-0@2
2022-09-15 15:36:34.496 DEBUG 71184 --- [o73657031-0-C-1] .a.RecordMessagingMessageListenerAdapter : Processing [GenericMessage [payload=test, headers={kafka_offset=2, kafka_consumer=org.apache.kafka.clients.consumer.KafkaConsumer@1582e8e4, kafka_correlationId=[B@2a266829, kafka_timestampType=CREATE_TIME, kafka_deliveryAttempt=1, kafka_replyTopic=[B@3dad3e81, kafka_receivedPartitionId=0, kafka_receivedTopic=so73657031, kafka_receivedTimestamp=1663270594381, kafka_groupId=so73657031}]]
test
2022-09-15 15:36:34.499 DEBUG 71184 --- [o73657031-0-C-1] .a.RecordMessagingMessageListenerAdapter : Listener method returned result [TEST] - generating response message for it
TEST
so73657031-0@3
2022-09-15 15:36:34.519 DEBUG 71184 --- [o73657031-0-C-1] .a.RecordMessagingMessageListenerAdapter : Processing [GenericMessage [payload=oneWay, headers={kafka_offset=3, kafka_consumer=org.apache.kafka.clients.consumer.KafkaConsumer@1582e8e4, kafka_timestampType=CREATE_TIME, kafka_deliveryAttempt=1, kafka_receivedPartitionId=0, kafka_receivedTopic=so73657031, kafka_receivedTimestamp=1663270594514, kafka_groupId=so73657031}]]
oneWay
2022-09-15 15:36:34.519 DEBUG 71184 --- [o73657031-0-C-1] .a.RecordMessagingMessageListenerAdapter : Listener method returned result [ONEWAY] - generating response message for it
2022-09-15 15:36:34.519 DEBUG 71184 --- [o73657031-0-C-1] .a.RecordMessagingMessageListenerAdapter : No replyTopic to handle the reply: ONEWAY

【讨论】:

  • 感谢 Gary 的快速演示。我可以看到您正在使用 spring 默认容器工厂作为侦听器。虽然 ReplyingTemplate 扩展了 KafkaTemplate 如果我使用我的 customListenerFactory 会有任何问题吗?基本上 setReplytemplate 将如何区分两个不同的模板(生产者模板)。
  • 复制/粘贴示例时我错过了一些代码;我在rkt 工厂方法中设置了replyTemplate。已编辑。设置容器工厂时使用普通模板的bean名称replyTemplate。
  • 谢谢加里。想知道在这种情况下确认是如何工作的。由于从侦听器(消费者)方面我们将同步和异步调用都包装在一个方法下,因此需要设置什么值来提交偏移量?是 Manual 还是 Manual_Immediate?我没有批量记录..
  • 回复容器不应有任何手动提交选项;否则不会提交任何偏移量;容器将在每次轮询后提交回复偏移量(默认情况下),无论轮询返回多少条记录,或者如果您将AckMode 设置为RECORD,则在每条记录之后。您的消费者也是如此;无需手动提交。
猜你喜欢
  • 2020-10-22
  • 2015-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
相关资源
最近更新 更多