使用KafkaListener将消息作为ASCII字符串接收

问题描述 投票:0回答:1

我正在使用Spring Framework的KafkaListener接口来收听Kafka主题。代码正在运行,但我猜是收到ASCII字符串中的消息。我不太清楚为什么会这样。

这是我的代码:

 import org.slf4j.Logger; 
 import org.slf4j.LoggerFactory; 
 import org.springframework.kafka.annotation.KafkaListener;
 import org.springframework.messaging.handler.annotation.Payload;
 import org.springframework.stereotype.Service;

 @Service 
 public class Receiver {
     private static final Logger LOG = LoggerFactory.getLogger(Receiver.class);

     @KafkaListener(topics = "mongoDBTest", groupId = "test")
     public void listen(@Payload String cMessage) {
         LOG.info("received message=" + cMessage);
         Application.print();
    } 
}

当消费时“测试”,我收到“收到消息= 116,101,115,116”作为输出。

java spring apache-kafka
1个回答
0
投票

嗨,看起来有人以错误的方式消费消息,而不仅仅是字符串。如果你可以在那个部分修复它 - 这太棒了。

否则,您需要将这些字节解码为普通字符串。请试试

String[] split = cMessage.split(",");
byte[] bytes = new byte[split.length];
for (int i = 0; i < split.length; i++) {
    bytes[i] = Byte.parseByte(split[i]);
}
LOG.info("received message=" + new String(bytes));
© www.soinside.com 2019 - 2024. All rights reserved.