搭建 Kafka Connect 数据同步管道

适用场景

需要把数据库、文件或消息系统实时同步到 Kafka,或把 Kafka 数据写入 Elasticsearch、对象存储、数据仓库。Kafka Connect 用配置而不是代码实现连接器管理。

前置条件

步骤

  1. 准备 Connect 配置:
cat > connect-distributed.properties <<'EOF'
bootstrap.servers=kafka1:9092,kafka2:9092,kafka3:9092
group.id=connect-cluster
key.converter=org.apache.kafka.connect.json.JsonConverter
value.converter=org.apache.kafka.connect.json.JsonConverter
key.converter.schemas.enable=false
value.converter.schemas.enable=false
offset.storage.topic=connect-offsets
offset.storage.replication.factor=3
config.storage.topic=connect-configs
config.storage.replication.factor=3
status.storage.topic=connect-status
status.storage.replication.factor=3
plugin.path=/opt/kafka/plugins
EOF
  1. 启动分布式 Worker:
connect-distributed.sh connect-distributed.properties
curl -s http://localhost:8083/ | jq
  1. 安装 Debezium 等插件到 plugin.path,重启 Worker。

  2. 创建 Source Connector:

curl -X POST http://localhost:8083/connectors \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "mysql-source",
    "config": {
      "connector.class": "io.debezium.connector.mysql.MySqlConnector",
      "tasks.max": "1",
      "database.hostname": "mysql",
      "database.port": "3306",
      "database.user": "debezium",
      "database.password": "***",
      "database.server.id": "184054",
      "topic.prefix": "cdc",
      "database.include.list": "app",
      "schema.history.internal.kafka.bootstrap.servers": "kafka1:9092",
      "schema.history.internal.kafka.topic": "schema-changes.app"
    }
  }'
  1. 创建 Sink Connector:
curl -X POST http://localhost:8083/connectors \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "es-sink",
    "config": {
      "connector.class": "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector",
      "tasks.max": "2",
      "topics": "cdc.app.orders",
      "connection.url": "http://elasticsearch:9200",
      "key.ignore": "true",
      "schema.ignore": "true"
    }
  }'
  1. 检查连接器和任务状态:
curl -s http://localhost:8083/connectors | jq
curl -s http://localhost:8083/connectors/mysql-source/status | jq
curl -s http://localhost:8083/connectors/mysql-source/tasks | jq

验证

回滚

常见坑

相关命令