【问题标题】:Apache Pulsar schema validate with json stringApache Pulsar 模式使用 json 字符串验证
【发布时间】:2020-07-02 20:32:48
【问题描述】:

在我的例子中,我有一些原始 JSON 字符串数据发送到主题并且无法对 POJO 类进行硬编码,我想使用 pulsar 模式特性来验证结构。我有一个主题“我的主题”并与下面的 JSON 模式相关联,然后我尝试传输一些消息。

var producer = client.newProducer(Schema.AUTO_PRODUCE_BYTES();
producer.send("{\"y\": 1}".getBytes()); // here! the value is 1(number) not string.

var reader = client.newReader(Schema.AUTO_CONSUME())
var message = reader.readNext();
I got {"y": 1}

我的问题是脉冲星模式是如何工作的?邮件应该被拒绝。

{
  "version": 1,
  "schemaInfo": {
    "name": "my-topic",
    "schema": {
      "type": "record",
      "name": "Data",
      "namespace": "com.iot.test",
      "fields": [
        {
          "name": "y",
          "type": [
            "null",
            "string"
          ]
        }
      ]
    },
    "type": "JSON",
    "properties": {
      "__alwaysAllowNull": "true"
    }
  }
}

【问题讨论】:

    标签: apache-pulsar pulsar


    【解决方案1】:

    我的错。只需要设置

    v2.5.0
    bin/pulsar-admin namespaces set-is-allow-auto-update-schema --disable iot/test
    
    v2.4.2
    bin/pulsar-admin namespaces set-schema-autoupdate-strategy --disable iot/test
    

    【讨论】:

      【解决方案2】:

      Schema.AUTO_PRODUCE_BYTES 设置对于将数据从生产者传输到具有架构的 Pulsar 主题非常有用,因为它确保发送的消息与主题的架构兼容。但是,我看不到您在哪里为该主题指定了架构。

      当您连接类型化的生产者或消费者时,会自动为主题分配架构,例如

      Producer producer = client.newProducer(JSONSchema.of(SensorReading.class))
          .topic("sensor-data")
          .sendTimeout(3, TimeUnit.SECONDS)
          .create();
      

      但是你已经声明你不能这样做,因为你“不能硬编码 POJO”。因此,将模式分配给主题(因此它可以强制消息模式兼容性)的唯一其他选择是使用 REST API calls 进行手动模式管理。

      根据您的架构,您的架构定义文件如下所示:

      {
        "type": "JSON",
        "schema": "{\"type\":\"record\",\"name\":\"Data\",\"namespace\":\"com.iot.test\",\"fields\":[{\"name\":\"y\",\"type\":[\"null\",\"string\"],\"default\":null}}",
        "properties": {}
      }
      

      HTH

      【讨论】:

      • 对不起,我的英语很差,我已经通过 pulsar admin java API 指定了模式,我的问题是 y 的字段类型是一个字符串,但即使发送 int 是有效的。 var producer = client.newProducer(Schema.AUTO_PRODUCE_BYTES(); producer.send("{\"y\": 1}".getBytes()); // here! the value is 1(number) not string.
      • 您能否发布以下命令的输出,显示与该主题相关的架构? pulsar-admin schemas get <topic-name> ?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多