如何用Java向kafka发送json数据
2个回答
展开全部
发送json也庆雹可以看成字符串处答差竖理
We have 2 Options as listed below
1) If we intend to send custom java objects to producer, We need to create a serializer which implements org.apache.kafka.common.serialization.Serializer and pass that Serializer class during creation of your producer
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 during send follow the process
Java Object -> String (Preferrably JSON represenation instead of toString)->byteArray
We have 2 Options as listed below
1) If we intend to send custom java objects to producer, We need to create a serializer which implements org.apache.kafka.common.serialization.Serializer and pass that Serializer class during creation of your producer
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 during send follow the process
Java Object -> String (Preferrably JSON represenation instead of toString)->byteArray
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询