将数据从Kafka主题以JSON推送到PostgreSQL

时间:2019-07-23 06:41:50

标签: postgresql apache-kafka apache-kafka-connect confluent

生产者控制台: enter image description here

以下错误: enter image description here

connect-standalone.properties文件

bootstrap.servers=localhost:9092 
key.converter=org.apache.kafka.connect.json.JsonConverter 
value.converter=org.apache.kafka.connect.json.JsonConverter 
key.converter.schemas.enable=true 
value.converter.schemas.enable=true

offset.storage.file.filename=/tmp/connect.offsets 
offset.flush.interval.ms=10000
plugin.path=/home/kafka/confluent-5.2.1/share/java

connect-post.properties文件

name=sink-postgres
connector.class=io.confluent.connect.jdbc.JdbcSinkConnector
tasks.max=2
topics=kafkada
connection.url=jdbc:postgresql://localhost:5432/kafkadb?
user=postgres&password=postgres
insert.mode=upsert
table.name.format=kafkatable
pk.mode=none
pk.fields=none
auto.create=true 
auto.evolve=false
offset.storage.file.filename=/tmp/post-sink.offsets

上述错误是由于我通过apache kafka执行./bin/connect-standalone.sh config / connect-standalone.properties config.postgresql.properties引起的。

然后,我已经尝试并实现了此链接中提到的流程:

https://hellokoding.com/kafka-connect-sinks-data-to-postgres-example-with-avro-schema-registry-and-python

但是,这里的数据是使用avro从Python代码生成的。但是对于我来说,我已经有来自kafka主题中传感器(JSON格式)的数据,我想发送给postgreSQL,而不是通过代码生成数据。

因此,如何实现从kafka主题向PostgreSQL发送数据的流程。

我已经共享了我的属性文件,如果需要更正,请告诉我。 我正在发送简单的json数据,例如“ {“ cust_id”:1313131,“ month”:12,“ expenses”:1313.13}“,我也尝试发送这种类型的数据,但仍然存在错误

样本json数据

 {
        "schema": {
            "type": "struct",
            "fields": [
                {
                    "type": "int",
                    "optional": false,
                    "field": "customer_id"
                },
                {
                    "type": "int",
                    "optional": true,
                    "field": "month"
                },

                {
                    "type": "string",
                    "optional": true,
                    "field": "amount_paid"
                }
            ],
            "optional": false,
            "name": "msgschema"
        },
        "payload": {
           "cust_id": 13, 
           "month": 12, 
           "expenses": 1313.13
        }
    }

我有一个名为kafkatable的表,该表具有使用

创建的列名((customer_id,month,amount_paid))

“ CREATE TABLE kafkatable(customer_id int8,month int4,amount_paid decimal(9,2));”

3 个答案:

答案 0 :(得分:1)

我通过进行以下更改解决了该错误

  1. insert.mode = insert
  2. 注释table.name.format = kafkatable,因为表将通过自动创建    创建
  3. 从connection.url行的末尾删除问号。
  4. pk.fields不应在此保留,请确保提供列名    避免并发症。
  5. PostgreSQL不支持
  6. int32,因此当我将其更改为int8时,它工作正常。
  7. 架构和有效负载中的字段具有不同的名称,请确保输入相同的名称。

答案 1 :(得分:0)

Kafka Connect是Apache Kafka的一部分,非常适合此操作。您可以通过一般here了解有关Kafka Connect的更多信息。

要将数据从Kafka主题流式传输到Postgres(或任何其他数据库),请使用JDBC Sink连接器,您可以从here获得该连接器。

答案 2 :(得分:0)

在“连接JSON模式”中,int不是有效类型。您需要更加具体,例如int32

https://github.com/apache/kafka/blob/trunk/connect/json/src/main/java/org/apache/kafka/connect/json/JsonSchema.java#L45