from type [java.lang.String] to type [org. apache.kafka.clients.consumer.ConsumerRecord<? ?>

枫树湾河桥發表於2024-08-08

kafka消費訊息的時候,報錯No converter found capable of converting from type [java.lang.String] to type [org. apache.kafka.clients.consumer.ConsumerRecord<? ?>,

沒有消費到資料,這種情況可能是傳送方傳送的資料是封裝了多個ConsumerRecord<? ?>物件傳送過來的,需要用ConsumerRecords<? ?> 來接收,該物件與前面物件相比後面多了一個 s ,透過對ConsumerRecords<? ?>遍歷可以獲取多個ConsumerRecord<?, ?>物件,具體程式碼如下:

import com.alibaba.fastjson.JSON;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

@Component
public class Test{

//多個ConsumerRecord<?, ?>物件接收
@KafkaListener(topics = {"TestTopic01"})
public void consumerMessage01(ConsumerRecords<?, ?> message) {
Iterator<? extends ConsumerRecord<?, ?>> iterator = message.iterator();
while (iterator.hasNext()){
ConsumerRecord<?, ?> next = iterator.next();
Optional optional =Optional.ofNullable(next.value());
//使用 isPresent() 方法判斷該物件是否包含非 null 的值
if(optional.isPresent()){
Object msg =optional.get();
//TestEntity是業務中使用到的實體物件
TestEntity testEntity = JSON.parseObject(msg.toString(),TestEntity.class);
}
}

}

//單個ConsumerRecord<?, ?>物件接收
@KafkaListener(topics = {"testTopic02"})
public void consumerMessage02(ConsumerRecord<?, ?> message) {

Optional optional =Optional.ofNullable(message.value());
Object msg =optional.get();
TestEntity testEntity = JSON.parseObject(msg.toString(),TestEntity.class);
}
————————————————

版權宣告:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連結和本宣告。

原文連結:https://blog.csdn.net/k0307x1990y/article/details/130356983

相關文章