Kafka AVRO Consumer:MySQL Decimal到Java Decimal

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

我正在尝试使用MySQL表中的记录,该表包含3列(Axis, Price, lastname),其数据类型分别为(int, decimal(14,4), varchar(50))

我插入了一条记录,其中包含以下数据(1, 5.0000, John)

以下Java代码(使用Confluent平台中MySQL Connector创建的主题中的AVRO记录)读取十进制列:Price,作为java.nio.HeapByteBuffer类型,因此当我收到时,我无法达到列的值它。

有没有办法将接收的数据提取或转换为Java十进制或双数据类型?

这是MySQL Connector属性文件: -

{
  "name": "mysql-source",
  "config": {
  "connector.class": "io.confluent.connect.jdbc.JdbcSourceConnector",
   "key.converter": "io.confluent.connect.avro.AvroConverter",
   "key.converter.schema.registry.url": "http://localhost:8081",
   "value.converter": "io.confluent.connect.avro.AvroConverter",
   "value.converter.schema.registry.url": "http://localhost:8081",
   "incrementing.column.name": "Axis",
   "tasks.max": "1",
   "table.whitelist": "ticket",
   "mode": "incrementing",
   "topic.prefix": "mysql-",
   "name": "mysql-source",
   "validate.non.null": "false",
   "connection.url": "jdbc:mysql://localhost:3306/ticket? 
   user=user&password=password"
   }
}

这是代码: -

    public static void main(String[] args) throws InterruptedException, 
     IOException {

        Properties props = new Properties();

        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");


        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, 
        "org.apache.kafka.common.serialization.StringDeserializer");
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, 
        "io.confluent.kafka.serializers.KafkaAvroDeserializer");
        props.put("schema.registry.url", "http://localhost:8081");

        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

        String topic = "sql-ticket";
final Consumer<String, GenericRecord> consumer = new KafkaConsumer<String, GenericRecord>(props);
consumer.subscribe(Arrays.asList(topic));

try {
  while (true) {
    ConsumerRecords<String, GenericRecord> records = consumer.poll(100);
    for (ConsumerRecord<String, GenericRecord> record : records) {
      System.out.printf("value = %s \n", record.value().get("Price"));
    }
  }
} finally {
  consumer.close();
}

}

enter image description here

java mysql apache-kafka apache-kafka-connect confluent
1个回答
0
投票

好吧,所以我终于找到了解决方案。

Heapbytebuffer需要转换为byte[]数组,然后我使用BigInteger构造从创建的字节数组中的值,然后我创建了一个BigDecimal变量,它接受BigInteger的值,我用movePointLeft(4)设置小数点,这是规模(在我的情况下:4)一切都按预期工作。

    ByteBuffer buf = (ByteBuffer) record.value().get(("Price"));
    byte[] arr = new byte[buf.remaining()];
    buf.get(arr);
    BigInteger bi =new BigInteger(1,arr);
    BigDecimal bd = new BigDecimal(bi).movePointLeft(4);
    System.out.println(bd);

结果如下(左边是输出,右边是MySQL): -

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.