首页 > 解决方案 > 使用 Ruby 代码和 avro_turf gem 对消息进行编码失败,并出现“数据不是模式示例”错误

问题描述

我正在尝试使用 Ruby 和 AvroTurf 制作一堆事件。当我从终端执行此操作时,一切正常。我正在启动控制台 kafka:

./kafka-avro-console-producer --topic test.topic --bootstrap-server kafka:9092 \
        --property key.schema='{"type":"string"}' \
        --property schema.registry.url=http://schema.registry:8081 \
        --property value.schema="$(< /path/to/schema/schema.avsc)" \
        --property parse.key=true \
        --property key.separator=":"

然后我自己发送键值消息:

"test":{"first_name":{"string":"stack"}, "last_name":{"string":"overflow"}}

它正在编码并成功发送 - 相应的记录出现在 KaDeck 中。


当我尝试使用 AvroTurf 在 Ruby 代码中编码相同的消息时,我开始遇到问题。

require 'avro_turf'

avro = AvroTurf.new(schemas_path: 'path/to/kafka_schemas')
avro.load_schemas!
avro.encode({"first_name":{"string":"stack"}, "last_name":{"string":"overflow"}}, schema_name: 'test')
>> The datum {"string"=>"stack"} is not an example of schema ["string","null"]

请注意,当我尝试以下格式时,我可以成功编码消息 - 反之亦然,在终端执行中我不能使用这种格式{"first_name":"stack", "last_name":"overflow"},因为SerializationException

avro.encode({"first_name":"stack", "last_name":"overflow"}, schema_name: 'test')
>> "Obj\u0001\u00 .... "

但问题是这种格式不适合我的任务。我需要这些{"key": {"string": "value"}}格式才能继续。我已经尝试了我能想到的一切 - 一些帮助将不胜感激。

我正在使用的模式(本地和模式注册表中的模式):

// test.avsc
{
  "name": "test",
  "type": "record",
  "fields": [
    { "name": "first_name", "type": [ "string", "null" ] },
    { "name": "last_name",  "type": [ "string", "null" ] }
  ]
}

如果我可以提供任何其他信息,请告诉我。提前致谢!

标签: rubyapache-kafkaavro

解决方案


推荐阅读