如何用Java向kafka发送json数据
发布网友
发布时间:2022-04-24 01:10
我来回答
共2个回答
热心网友
时间:2023-10-17 12:49
发送json也可以看成字符串处理
We have 2 Options as listed below
1) If we intend to send custom java objects to procer, We need to create a serializer which implements org.apache.kafka.common.serialization.Serializer and pass that Serializer class ring creation of your procer
Code Reference below
public class PayloadSerializer implements org.apache.kafka.common.serialization.Serializer {
public void configure(Map map, boolean b) {
}
public byte[] serialize(String s, Object o) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
byte[] b = baos.toByteArray();
return b;
} catch (IOException e) {
return new byte[0];
}
}
public void close() {
}
}
And set the value serializer accordingly
<entry key="value.serializer"
value="com.spring.kafka.PayloadSerializer" />
2) No need to create custom serializer class. Use the existing ByteArraySerializer, but ring send follow the process
Java Object -> String (Preferrably JSON represenation instead of toString)->byteArray
热心网友
时间:2023-10-17 12:49
文档,序列化成String就行了