如何验证Kafka消费者收到消息

时间:2020-01-30 07:33:24

标签: java spring-boot apache-kafka

我的应用程序中有一个场景,我正在向端点发出REST请求,并且我只希望当kafka使用者从生产者那里收到消息时将响应发送回去。我在使用者上有一个侦听器,但是我不确定该侦听器和API执行之间如何链接,以便它停止它,直到使用者收到一条消息为止。有任何想法吗?谢谢

编辑这是我要尝试的示例

这是消费者的收听者

 @Component
    public class ReplyingKafkaConsumer {

        @KafkaListener(topics = "${kafka.topic.request-topic}")
        @SendTo
        public UserRequest listen(UserRequest request) throws InterruptedException {

            UserRequest response = new UserRequest();
            response.setCompanyId(68L);
            response.setCompanyName("AdiBas");
            response.setEmail("adibas@gmail.com");
            response.setUserId(102L);

            return response;
        }

我需要在此REST API中倾听使用者的声音

 @ResponseBody
    @PostMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public UserRequest post(@RequestBody UserRequest request) throws InterruptedException, ExecutionException {
        // create producer record
        ProducerRecord<String, UserRequest> record = new ProducerRecord<>(requestTopic, request);
        // set reply topic in header
        record.headers().add(new RecordHeader(KafkaHeaders.REPLY_TOPIC, requestReplyTopic.getBytes()));
        // post in kafka topic
        RequestReplyFuture<String, UserRequest, UserRequest> sendAndReceive = kafkaTemplate.sendAndReceive(record);

        // confirm if producer produced successfully
        SendResult<String, UserRequest> sendResult = sendAndReceive.getSendFuture().get();

        //print all headers
        sendResult.getProducerRecord().headers().forEach(header -> System.out.println(header.key() + ":" + header.value().toString()));

        // get consumer record
        ConsumerRecord<String, UserRequest> consumerRecord = sendAndReceive.get();
        // return consumer value
        return consumerRecord.value();
    }

0 个答案:

没有答案