【发布时间】:2021-05-16 15:00:48
【问题描述】:
到目前为止,我正在从 avsc 架构文件创建 avro 消息。使用下面的代码 sn-p
static byte[] fromJasonToAvro(String json, String schemastr) throws Exception {
InputStream input = new ByteArrayInputStream(json.getBytes());
DataInputStream din = new DataInputStream(input);
Schema schema = Schema.parse(schemastr);
Decoder decoder = DecoderFactory.get().jsonDecoder(schema, din);
DatumReader<Object> reader = new GenericDatumReader<Object>(schema);
Object datum = reader.read(null, decoder);
GenericDatumWriter<Object> w = new GenericDatumWriter<Object>(schema);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Encoder e = EncoderFactory.get().binaryEncoder(outputStream, null);
w.write(datum, e);
e.flush();
return outputStream.toByteArray();
}
public static void main(String[] args) throws Exception {
StringBuilder sb = new StringBuilder();
StringBuilder jsb = new StringBuilder();
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("RsvpAvroSchema.avsc");
InputStream js = classloader.getResourceAsStream("JsonMessage.dat");
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
InputStreamReader jisr = new InputStreamReader(js, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
BufferedReader jbr = new BufferedReader(jisr);
br.lines().forEach(line -> sb.append(line));
jbr.lines().forEach(line -> jsb.append(line));
System.out.println(sb);
System.out.println(jsb);
System.out.println(new String(fromJasonToAvro(jsb.toString(), sb.toString()), StandardCharsets.UTF_8));
但我也使用 maven 插件从 avsc 创建了 avro 类(数据结构)。但现在不确定如何使用 avro message data structure 的主类和 string json 消息来生成 avro 消息?
谁能分享一下怎么做?
更新:
如何从字符串 Json 创建 Avro 对象?我的项目中已经有可用的 avro 类。
第二次更新
public class AvroInstance {
static DecoderFactory DEFAULT_FACTORY = new DecoderFactory();
static DatumReader<Object> reader = new GenericDatumReader<Object>(RSVP.SCHEMA$);
static Object rsvpOB;
public Object avroInstance(String JsonString) {
try {
rsvpOB = reader.read(null, DEFAULT_FACTORY.jsonDecoder(RSVP.SCHEMA$, JsonString));
} catch (IOException e) {
e.printStackTrace();
}
return rsvpOB;
}
【问题讨论】:
-
您将 Avro 消息发送到哪里?卡夫卡主题?如果是这样,请将 Producer 配置为使用 KafkaAvroSerializer - 请参阅 docs.confluent.io/platform/current/schema-registry/…
-
@Kevin 我相信这样做的目的是不使用注册表stackoverflow.com/questions/67518900/…
标签: java json serialization avro