Flink消费Avro格式数据 - java

上游数据被封装为confluentAvro 格式(avro 格式的一种),使用flink 进行消费,

avro 版本 1.10.1 

以下为处理方式:

先编写 xxx.avsc文件,其格式如下:

​
{
    "namespace": "io.transwarp.de.bean",
    "type": "record",
    "name": "Cdkyeres",
    "fields": [
        {"name": "owner", "type": ["null", "string"], "default": null},
        {"name": "name", "type": ["null", "string"], "default": null},
        {"name": "rowid", "type": ["null", "string"], "default": null},
        {"name": "actseq", "type": ["null", "string"], "default": null},
        {"name": "jstime", "type": ["null", "string"], "default": null},
        {"name": "scntime", "type": ["null", "int"], "default": null},
        {"name": "sdbtype", "type": ["null", "string"], "default": null},
        {"name": "optype", "type": ["null", "string"], "default": null},
        {"name": "sync", "type": ["null", "int"], "default": null},
        {"name": "xid", "type": ["null", "string"], "default": null},
        {"name": "scn", "type": ["null", "string"], "default": null},
        {"name": "op", "type": ["null", "int"], "default": null},
        {"name": "org_no", "type": ["null", "string"], "default": null},
        {"name": "bbrq", "type": ["null", "string"], "default": null},
        {"name": "crt_no", "type": ["null", "string"], "default": null},
        {"name": "dkye", "type": ["null", "string"], "default": null},
        {"name": "ckye", "type": ["null", "string"], "default": null},
        {"name": "flag", "type": ["null", "string"], "default": null},
        {"name": "up_org_no", "type": ["null", "string"], "default": null}
    ]
}

​

:这里的 io.transwarp.de.bean 是生成的bean的路径,要提前想好 bean要放哪,不然改起来很麻烦

使用avro-tool 进行pojo 生成
java -jar jar包路径 compile schema avsc文件路径 .

把生成的pojo 放入项目中,在使用时,会调用其内部的一个方法 .getClassSchema() ,返回值本质就是 avsc文件里的内容,进行解析,封装成的schema。

因为使用了ConfluentRegistryAvroDeserializationSchema类的的 forGeneric() ,要求传入 一个schema对象,使用KafkaSource 与 FlinkKafkaConsumer 的操作如出一辙

FlinkKafkaConsumer consumer = new FlinkKafkaConsumer(

          topic,
          ConfluentRegistryAvroDeserializationSchema.forGeneric(xxx.getschema(),registUrl)
          properties
);

env.addSource(consumer);

或者不生成pojo,进行如下操作:

Schema schema = new Schema.Parser().parse(new File("user.avsc"));

GenericRecord user1= new GenericData.Record(schema);


user1.put("name", "Ben");
user1.put("favorite_number", 7);
user1.put("favorite_color", "red");

注:genericRecord 可看成map 

另外,FlinkKafkaConsumer 1.14版本已标注过时,1.17版本已移除

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值