Todos los productos
Search
Centro de documentos

Tablestore:Sync Kafka data to a data table

Última actualización: Sep 03, 2026

El Tablestore sink connector consulta mensajes en Kafka desde los topics suscritos, analiza los registros de mensajes e importa los datos por lotes a una tabla de datos de Tablestore.

Requisitos previos

  • Kafka está instalado y tanto ZooKeeper como Kafka se están ejecutando. Para obtener más información, consulte la documentación oficial de Kafka.

  • Active el servicio Tablestore y luego cree una instancia y una tabla de datos. Para obtener más información, consulte Quick Start for wide table models.

    Nota

    También puede usar el Tablestore sink connector para crear automáticamente la tabla de datos de destino. Para ello, establezca el parámetro auto.create en true.

  • Obtenga un accesskey. Para obtener más información, consulte Create an AccessKey.

Paso 1: Desplegar el Tablestore Sink Connector

  1. Puede obtener el Tablestore sink connector de una de las siguientes maneras.

    • Descargue y compile el código fuente desde GitHub. El código fuente está disponible en Código fuente del Tablestore Sink Connector.

      1. Ejecute el siguiente comando para descargar el código fuente del Tablestore sink connector.

        git clone https://github.com/aliyun/kafka-connect-tablestore.git
      2. Vaya al directorio del código fuente descargado y ejecute el siguiente comando para empaquetar el código mediante Maven.

        mvn clean package -DskipTests

        Una vez completada la compilación, el paquete generado, como kafka-connect-tablestore-1.0.jar, se almacena en el directorio target.

    • Descargue el paquete kafka-connect-tablestore compilado.

  2. Copie el paquete al directorio $KAFKA_HOME/libs en cada nodo.

Paso 2: Iniciar el Tablestore Sink Connector

El Tablestore sink connector admite dos modos de ejecución: standalone y distributed. Elija un modo según sus requisitos.

Modo Standalone

  1. Modifique el archivo de configuración del worker connect-standalone.properties y el archivo de configuración del connector connect-tablestore-sink-quickstart.properties según sea necesario.

    • Ejemplo del archivo de configuración del worker connect-standalone.properties

      La configuración del worker incluye parámetros como la configuración de conexión de Kafka, el formato de serialización y la frecuencia de confirmación de offsets. Este ejemplo se basa en la documentación oficial de Kafka. Para obtener más información, consulte Kafka Connect.

      # Licensed to the Apache Software Foundation (ASF) under one or more
      # contributor license agreements.  See the NOTICE file distributed with
      # this work for additional information regarding copyright ownership.
      # The ASF licenses this file to You under the Apache License, Version 2.0
      # (the "License"); you may not use this file except in compliance with
      # the License.  You may obtain a copy of the License at
      #
      #    http://www.apache.org/licenses/LICENSE-2.0
      #
      # Unless required by applicable law or agreed to in writing, software
      # distributed under the License is distributed on an "AS IS" BASIS,
      # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      # See the License for the specific language governing permissions and
      # limitations under the License.
      
      # These are defaults. This file just demonstrates how to override some settings.
      bootstrap.servers=localhost:9092
      
      # The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will
      # need to configure these based on the format they want their data in when loaded from or stored into Kafka
      key.converter=org.apache.kafka.connect.json.JsonConverter
      value.converter=org.apache.kafka.connect.json.JsonConverter
      # Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply
      # it to
      key.converter.schemas.enable=true
      value.converter.schemas.enable=true
      
      offset.storage.file.filename=/tmp/connect.offsets
      # Flush much faster than normal, which is useful for testing/debugging
      offset.flush.interval.ms=10000
      
      # Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins
      # (connectors, converters, transformations). The list should consist of top level directories that include 
      # any combination of: 
      # a) directories immediately containing jars with plugins and their dependencies
      # b) uber-jars with plugins and their dependencies
      # c) directories immediately containing the package directory structure of classes of plugins and their dependencies
      # Note: symlinks will be followed to discover dependencies or plugins.
      # Examples: 
      # plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors,
      #plugin.path=
    • Ejemplo de archivo de configuración del connector: connect-tablestore-sink-quickstart.properties

      La configuración del connector incluye parámetros como la clase del connector, la conexión a Tablestore y la asignación de datos. Para obtener más información, consulte Configuration.

      # Set the connector name.
      name=tablestore-sink
      # Specify the connector class.
      connector.class=TableStoreSinkConnector
      # Set the maximum number of tasks.
      tasks.max=1
      # Specify the list of Kafka topics from which to export data.
      topics=test
      
      # The following are the Tablestore connection parameter settings.
      # The endpoint of the Tablestore instance.
      tablestore.endpoint=https://xxx.xxx.ots.aliyuncs.com
      # Your AccessKey ID and AccessKey secret.
      tablestore.access.key.id =xxx
      tablestore.access.key.secret=xxx
      # The Tablestore instance name.
      tablestore.instance.name=xxx
      
      # A format string for the destination Tablestore table name. <topic> is a placeholder for the original topic name. The default value is <topic>.
      # Examples:
      # table.name.format=kafka_<topic>, message records from the 'test' topic will be written to the 'kafka_test' data table.
      # table.name.format=
      
      # The primary key mode. The default value is kafka.
      # The primary key of the Tablestore data table will be composed of <topic>_<partition> (the Kafka topic and partition, separated by "_") and <offset> (the offset of the message record in the partition).
      # primarykey.mode=
      
      # Automatically create the destination table. The default value is false.
      auto.create=true
  2. Vaya al directorio $KAFKA_HOME y ejecute el siguiente comando para iniciar el connector en modo standalone.

    bin/connect-standalone.sh config/connect-standalone.properties config/connect-tablestore-sink-quickstart.properties

Modo Distributed

  1. Modifique el archivo de configuración del worker connect-distributed.properties según sea necesario.

    La configuración del worker incluye parámetros como la configuración de conexión de Kafka, el formato de serialización y la frecuencia de confirmación de offsets. También especifica los topics que almacenan información para cada connector. Debe crear estos topics con antelación. Este ejemplo se basa en la documentación oficial de Kafka. Para obtener más información, consulte Kafka Connect.

    • offset.storage.topic: Un topic compacto utilizado para almacenar los offsets de cada connector.

    • config.storage.topic: Un topic compacto utilizado para almacenar las configuraciones de connectors y tareas. El número de particiones para este topic debe establecerse en 1.

    • status.storage.topic: Un topic compacto utilizado para almacenar información de estado de Kafka Connect.

    ##
    # Licensed to the Apache Software Foundation (ASF) under one or more
    # contributor license agreements.  See the NOTICE file distributed with
    # this work for additional information regarding copyright ownership.
    # The ASF licenses this file to You under the Apache License, Version 2.0
    # (the "License"); you may not use this file except in compliance with
    # the License.  You may obtain a copy of the License at
    #
    #    http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    ##
    
    # This file contains some of the configurations for the Kafka Connect distributed worker. This file is intended
    # to be used with the examples, and some settings may differ from those used in a production system, especially
    # the `bootstrap.servers` and those specifying replication factors.
    
    # A list of host/port pairs to use for establishing the initial connection to the Kafka cluster.
    bootstrap.servers=localhost:9092
    
    # unique name for the cluster, used in forming the Connect cluster group. Note that this must not conflict with consumer group IDs
    group.id=connect-cluster
    
    # The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will
    # need to configure these based on the format they want their data in when loaded from or stored into Kafka
    key.converter=org.apache.kafka.connect.json.JsonConverter
    value.converter=org.apache.kafka.connect.json.JsonConverter
    # Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply
    # it to
    key.converter.schemas.enable=true
    value.converter.schemas.enable=true
    
    # Topic to use for storing offsets. This topic should have many partitions and be replicated and compacted.
    # Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
    # the topic before starting Kafka Connect if a specific topic configuration is needed.
    # Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
    # Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
    # to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
    offset.storage.topic=connect-offsets
    offset.storage.replication.factor=1
    #offset.storage.partitions=25
    
    # Topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated,
    # and compacted topic. Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
    # the topic before starting Kafka Connect if a specific topic configuration is needed.
    # Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
    # Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
    # to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
    config.storage.topic=connect-configs
    config.storage.replication.factor=1
    
    # Topic to use for storing statuses. This topic can have multiple partitions and should be replicated and compacted.
    # Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
    # the topic before starting Kafka Connect if a specific topic configuration is needed.
    # Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
    # Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
    # to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
    status.storage.topic=connect-status
    status.storage.replication.factor=1
    #status.storage.partitions=5
    
    # Flush much faster than normal, which is useful for testing/debugging
    offset.flush.interval.ms=10000
    
    # These are provided to inform the user about the presence of the REST host and port configs 
    # Hostname & Port for the REST API to listen on. If this is set, it will bind to the interface used to listen to requests.
    #rest.host.name=
    #rest.port=8083
    
    # The Hostname & Port that will be given out to other workers to connect to i.e. URLs that are routable from other servers.
    #rest.advertised.host.name=
    #rest.advertised.port=
    
    # Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins
    # (connectors, converters, transformations). The list should consist of top level directories that include 
    # any combination of: 
    # a) directories immediately containing jars with plugins and their dependencies
    # b) uber-jars with plugins and their dependencies
    # c) directories immediately containing the package directory structure of classes of plugins and their dependencies
    # Examples: 
    # plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors,
    #plugin.path=
  2. Vaya al directorio $KAFKA_HOME y ejecute el siguiente comando para iniciar el connector en modo distributed.

    Importante

    Inicie el proceso del worker en cada nodo.

    bin/connect-distributed.sh config/connect-distributed.properties
  3. Puede gestionar los connectors mediante la API REST. Para obtener más información, consulte API REST.

    1. Cree el archivo connect-tablestore-sink-quickstart.json en la ruta config y agregue el siguiente contenido de ejemplo.

      El archivo de configuración del connector especifica parámetros como pares clave-valor en formato JSON. Estos parámetros incluyen la clase del connector, la configuración de conexión a Tablestore y la asignación de datos. Para obtener más información, consulte Configuration.

      {
        "name": "tablestore-sink",
        "config": {
          "connector.class":"TableStoreSinkConnector",
          "tasks.max":"1",
          "topics":"test",
          "tablestore.endpoint":"https://xxx.xxx.ots.aliyuncs.com",
          "tablestore.access.key.id":"xxx",
          "tablestore.access.key.secret":"xxx",
          "tablestore.instance.name":"xxx",
          "table.name.format":"<topic>",
          "primarykey.mode":"kafka",
          "auto.create":"true"
        }
      }
    2. Ejecute el siguiente comando para iniciar el Tablestore sink connector.

      curl -i -k  -H "Content-type: application/json" -X POST -d @config/connect-tablestore-sink-quickstart.json http://localhost:8083/connectors

      http://localhost:8083/connectors es la dirección del servicio REST de Kafka. Modifique esta dirección según sea necesario.

Paso 3: Producir nuevos registros

  1. Vaya al directorio $KAFKA_HOME y ejecute el siguiente comando para iniciar un producer de consola.

    bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test

    Para obtener una descripción de los parámetros, consulte la siguiente tabla.

    Elemento de configuración

    Ejemplo

    Descripción

    --broker-list

    localhost:9092

    La dirección y el puerto del broker del clúster de Kafka.

    --topic

    test

    El nombre del topic. El topic se crea automáticamente de forma predeterminada cuando se inicia el Tablestore Sink Connector. También puede crear el topic manualmente.

  2. Escriba mensajes en el topic test.

    • Mensaje de tipo Struct

      {
          "schema":{
              "type":"struct",
              "fields":[
                  {
                      "type":"int32",
                      "optional":false,
                      "field":"id"
                  },
                  {
                      "type":"string",
                      "optional":false,
                      "field":"product"
                  },
                  {
                      "type":"int64",
                      "optional":false,
                      "field":"quantity"
                  },
                  {
                      "type":"double",
                      "optional":false,
                      "field":"price"
                  }
              ],
              "optional":false,
              "name":"record"
          },
          "payload":{
              "id":1,
              "product":"foo",
              "quantity":100,
              "price":50
          }
      }
    • Mensaje de tipo Map

      {
          "schema":{
              "type":"map",
              "keys":{
                  "type":"string",
                  "optional":false
              },
              "values":{
                  "type":"int32",
                  "optional":false
              },
              "optional":false
          },
          "payload":{
              "id":1
          }
      }
  3. Inicie sesión en la consola de Tablestore para consultar los datos.

    Se crea automáticamente una tabla de datos llamada test en la instancia de Tablestore. La tabla de resultados de la consulta contiene las siguientes columnas: topic_partition (clave principal), offset (clave principal), id, price, product y quantity. En los datos de ejemplo, el primer registro tiene topic_partition=test_3, offset=0, id=AAAAAQ== y los demás campos están vacíos. El segundo registro tiene topic_partition=test_34, offset=0, id=1, price=50.0, product=foo y quantity=100.