欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

kafka connector 使用总结以及自定义connector开发

程序员文章站 2022-09-27 15:09:45
Kafaka connect 是一种用于在Kafka和其他系统之间可扩展的、可靠的流式传输数据的工具。它使得能够快速定义将大量数据集合移入和移出Kafka的连接器变得简单。Kafka Connect可以从数据库或应用程序服务器收集数据到Kafka topic,使数据可用于低延迟的流处理。导出作业可以 ......

kafaka connect 是一种用于在kafka和其他系统之间可扩展的、可靠的流式传输数据的工具。它使得能够快速定义将大量数据集合移入和移出kafka的连接器变得简单。kafka connect可以从数据库或应用程序服务器收集数据到kafka topic,使数据可用于低延迟的流处理。导出作业可以将数据从kafka topic传输到二次存储和查询系统,或者传递到批处理系统以进行离线分析。

kafaka connect的核心组件:
source:负责将外部数据写入到kafka的topic中。
sink:负责从kafka中读取数据到自己需要的地方去,比如读取到hdfs,hbase等。

kafka connector 使用总结以及自定义connector开发
connectors :通过管理任务来协调数据流的高级抽象
tasks:数据写入kafk和从kafka中读出数据的具体实现,source和sink使用时都需要task

kafka connector 使用总结以及自定义connector开发

workers:运行connectors和tasks的进程

kafka connector 使用总结以及自定义connector开发

converters:kafka connect和其他存储系统直接发送或者接受数据之间转换数据,

converter会把bytes数据转换成kafka connect内部的格式,也可以把kafka connect内部存储格式的数据转变成bytes,converter对connector来说是解耦的,所以其他的connector都可以重用,例如,使用了avro converter,那么jdbc connector可以写avro格式的数据到kafka,当然,hdfs connector也可以从kafka中读出avro格式的数据。

kafka connector 使用总结以及自定义connector开发

 

transforms:一种轻量级数据调整的工具
kafka connect 工作模式:
kafka connect 有两种工作模式:
standalone:在standalone模式中,所有的worker都在一个独立的进程中完成。
distributed:distributed模式具有高扩展性,以及提供自动容错机制。你可以使用一个group.ip来启动很多worker进程,在有效的worker进程中它们会自动的去协调执行connector和task,如果你新加了一个worker或者挂了一个worker,其他的worker会检测到然后在重新分配connector和task。

本文作者:张永清,转载请注明出处:https://www.cnblogs.com/laoqing/p/11927958.html 

在分布式模式下通过rest api来管理connector。
connector的常见管理操作api:

get /connectors – 返回所有正在运行的connector名。
post /connectors – 新建一个connector; 请求体必须是json格式并且需要包含name字段和config字段,name是connector的名字,config是json格式,必须包含你的connector的配置信息。
get /connectors/{name} – 获取指定connetor的信息。
get /connectors/{name}/config – 获取指定connector的配置信息。
put /connectors/{name}/config – 更新指定connector的配置信息。
get /connectors/{name}/status – 获取指定connector的状态,包括它是否在运行、停止、或者失败,如果发生错误,还会列出错误的具体信息。
get /connectors/{name}/tasks – 获取指定connector正在运行的task。
get /connectors/{name}/tasks/{taskid}/status – 获取指定connector的task的状态信息。
put /connectors/{name}/pause – 暂停connector和它的task,停止数据处理知道它被恢复。
put /connectors/{name}/resume – 恢复一个被暂停的connector。
post /connectors/{name}/restart – 重启一个connector,尤其是在一个connector运行失败的情况下比较常用
post /connectors/{name}/tasks/{taskid}/restart – 重启一个task,一般是因为它运行失败才这样做。
delete /connectors/{name} – 删除一个connector,停止它的所有task并删除配置。

如何开发自己的connector:

1、引入maven依赖。

        <dependency>
            <groupid>org.apache.kafka</groupid>
            <artifactid>connect-api</artifactid>
            <version>${kafka.version}</version>
        </dependency>

2、开发自定义的source

开发自定义的source 需要继承实现sourceconnector和sourcetask这两个抽象类,实现抽象类中的未实现的方法或者重写抽象类中的方法。

本文作者:张永清,转载请注明出处:https://www.cnblogs.com/laoqing/p/11927958.html 

a、开发自定义的sourceconnector

/**
 *
 */
public class examplesourceconnector extends sourceconnector{
    @override
    public void start(map<string, string> map) {

    }
    //返回需要指定的task
    @override
    public class<? extends task> taskclass() {
        return examplesourcetask.class;
    }
    //task的配置
    @override
    public list<map<string, string>> taskconfigs(int i) {
        return null;
    }

    @override
    public void stop() {

    }

    @override
    public configdef config() {
        return null;
    }

    @override
    public string version() {
        return appinfoparser.getversion();
    }
}

b、开发source对应的task

public class examplesourcetask extends sourcetask {
    @override
    public string version() {
        return new examplesourceconnector().version();
    }
    //任务启动
    @override
    public void start(map<string, string> map) {

    }
    //需要发送到kafka的数据。
    @override
    public list<sourcerecord> poll() throws interruptedexception {
        return null;
    }
    //任务停止
    @override
    public void stop() {

    }
}

3、开发自定义的sink

  开发自定义的sink 需要继承实现sinkconnector和sinktask这两个抽象类,实现抽象类中的未实现的方法或者重写抽象类中的方法。

a、开发自定义的sinkconnector

/**
 *
 */
public class examplesinkconnector extends sinkconnector{
    @override
    public void start(map<string, string> map) {

    }
    //指定task执行的类
    @override
    public class<? extends task> taskclass() {
        return examplesinktask.class;
    }
    //task对应的config
    @override
    public list<map<string, string>> taskconfigs(int i) {
        return null;
    }

    @override
    public void stop() {

    }
    //配置定义
    @override
    public configdef config() {
        return null;
    }

    @override
    public string version() {
        return appinfoparser.getversion();
    }
}

b、开发sink对应的task  

/**
 *
 */
public class examplesinktask extends sinktask {
    @override
    public string version() {
        return new examplesinkconnector().version();
    }
    //task启动
    @override
    public void start(map<string, string> map) {

    }
    //数据put
    @override
    public void put(collection<sinkrecord> collection) {

    }
    @override
    public void flush(map<topicpartition, offsetandmetadata> offsets){
    //task停止。
    }
    @override
    public void stop() {

    }
}

kafka connect configs

kafka connector 使用总结以及自定义connector开发

 开源的实现的比较好的connector项目:

 

kafka connector 使用总结以及自定义connector开发

kafka connector 使用总结以及自定义connector开发

 

 

 

kafka connector 使用总结以及自定义connector开发

 

 这里我们以 中的debezium-connector-mongodb 为例配置connector的standalone模式运行

从github中获取debezium-connector-mongodb-0.9.5.final.jar 包,放到kafka的libs目录下,并且把mongodb相关的jar包一起放入到libs下。

kafka connector 使用总结以及自定义connector开发

在config目录下新建对应的mongodb.properties 属性配置文件

name=mongodb
connector.class=io.debezium.connector.mongodb.mongodbconnector
mongodb.hosts=configs/10.100.xx.xx:27017
tasks.max=1
mongodb.name=mongo-test
#mongodb.user=root
#mongodb.password=123456
database.whitelist=kafkatest
collection.whitelist=kafkatest.kafkatest
connect.max.attempts=12
max.queue.size=8192
max.batch.size=2048
poll.interval.ms=1000
connect.backoff.initial.delay.ms=1000
connect.backoff.max.delay.ms=2000
mongodb.ssl.enabled=false
mongodb.ssl.invalid.hostname.allowed=false
snapshot.mode=initial
initial.sync.max.threads=2
tombstones.on.delete=true
mongodb.members.auto.discover=true
source.struct.version=v2

 配置解释如下:

详情参考:

property default description

name

 

unique name for the connector. attempting to register again with the same name will fail. (this property is required by all kafka connect connectors.)

connector.class

 

the name of the java class for the connector. always use a value of io.debezium.connector.mongodb.mongodbconnector for the mongodb connector.

mongodb.hosts

 

the comma-separated list of hostname and port pairs (in the form 'host' or 'host:port') of the mongodb servers in the replica set. the list can contain a single hostname and port pair. if mongodb.members.auto.discover is set to false, then the host and port pair should be prefixed with the replica set name (e.g., rs0/localhost:27017).

mongodb.name

 

a unique name that identifies the connector and/or mongodb replica set or sharded cluster that this connector monitors. each server should be monitored by at most one debezium connector, since this server name prefixes all persisted kafka topics emanating from the mongodb replica set or cluster.

mongodb.user

 

name of the database user to be used when connecting to mongodb. this is required only when mongodb is configured to use authentication.

mongodb.password

 

password to be used when connecting to mongodb. this is required only when mongodb is configured to use authentication.

mongodb.ssl.enabled

false

connector will use ssl to connect to mongodb instances.

mongodb.ssl.invalid.hostname.allowed

false

when ssl is enabled this setting controls whether strict hostname checking is disabled during connection phase. if true the connection will not prevent man-in-the-middle attacks.

database.whitelist

empty string

an optional comma-separated list of regular expressions that match database names to be monitored; any database name not included in the whitelist will be excluded from monitoring. by default all databases will be monitored. may not be used with database.blacklist.

database.blacklist

empty string

an optional comma-separated list of regular expressions that match database names to be excluded from monitoring; any database name not included in the blacklist will be monitored. may not be used with database.whitelist.

collection.whitelist

empty string

an optional comma-separated list of regular expressions that match fully-qualified namespaces for mongodb collections to be monitored; any collection not included in the whitelist will be excluded from monitoring. each identifier is of the form databasename.collectionname. by default the connector will monitor all collections except those in the local and admin databases. may not be used with collection.blacklist.

collection.blacklist

empty string

an optional comma-separated list of regular expressions that match fully-qualified namespaces for mongodb collections to be excluded from monitoring; any collection not included in the blacklist will be monitored. each identifier is of the form databasename.collectionname. may not be used with collection.whitelist.

snapshot.mode

initial

specifies the criteria for running a snapshot (eg. initial sync) upon startup of the connector. the default is initial, and specifies the connector reads a snapshot when either no offset is found or if the oplog no longer contains the previous offset. the never option specifies that the connector should never use snapshots, instead the connector should proceed to tail the log.

field.blacklist

empty string

an optional comma-separated list of the fully-qualified names of fields that should be excluded from change event message values. fully-qualified names for fields are of the form databasename.collectionname.fieldname.nestedfieldname, where databasename and collectionname may contain the wildcard (*) which matches any characters.

field.renames

empty string

an optional comma-separated list of the fully-qualified replacements of fields that should be used to rename fields in change event message values. fully-qualified replacements for fields are of the form databasename.collectionname.fieldname.nestedfieldname:newnestedfieldname, where databasename and collectionname may contain the wildcard (*) which matches any characters, the colon character (:) is used to determine rename mapping of field. the next field replacement is applied to the result of the previous field replacement in the list, so keep this in mind when renaming multiple fields that are in the same path.

tasks.max

1

the maximum number of tasks that should be created for this connector. the mongodb connector will attempt to use a separate task for each replica set, so the default is acceptable when using the connector with a single mongodb replica set. when using the connector with a mongodb sharded cluster, we recommend specifying a value that is equal to or more than the number of shards in the cluster, so that the work for each replica set can be distributed by kafka connect.

initial.sync.max.threads

1

positive integer value that specifies the maximum number of threads used to perform an intial sync of the collections in a replica set. defaults to 1.

tombstones.on.delete

true

controls whether a tombstone event should be generated after a delete event.
when true the delete operations are represented by a delete event and a subsequent tombstone event. when false only a delete event is sent.
emitting the tombstone event (the default behavior) allows kafka to completely delete all events pertaining to the given key once the source record got deleted.

snapshot.delay.ms

 

an interval in milli-seconds that the connector should wait before taking a snapshot after starting up;
can be used to avoid snapshot interruptions when starting multiple connectors in a cluster, which may cause re-balancing of connectors.

snapshot.fetch.size

0

specifies the maximum number of documents that should be read in one go from each collection while taking a snapshot. the connector will read the collection contents in multiple batches of this size.
defaults to 0, which indicates that the server chooses an appropriate fetch size.

the following advanced configuration properties have good defaults that will work in most situations and therefore rarely need to be specified in the connector’s configuration.

property default description

max.queue.size

8192

positive integer value that specifies the maximum size of the blocking queue into which change events read from the database log are placed before they are written to kafka. this queue can provide backpressure to the oplog reader when, for example, writes to kafka are slower or if kafka is not available. events that appear in the queue are not included in the offsets periodically recorded by this connector. defaults to 8192, and should always be larger than the maximum batch size specified in the max.batch.size property.

max.batch.size

2048

positive integer value that specifies the maximum size of each batch of events that should be processed during each iteration of this connector. defaults to 2048.

poll.interval.ms

1000

positive integer value that specifies the number of milliseconds the connector should wait during each iteration for new change events to appear. defaults to 1000 milliseconds, or 1 second.

connect.backoff.initial.delay.ms

1000

positive integer value that specifies the initial delay when trying to reconnect to a primary after the first failed connection attempt or when no primary is available. defaults to 1 second (1000 ms).

connect.backoff.max.delay.ms

1000

positive integer value that specifies the maximum delay when trying to reconnect to a primary after repeated failed connection attempts or when no primary is available. defaults to 120 seconds (120,000 ms).

connect.max.attempts

16

positive integer value that specifies the maximum number of failed connection attempts to a replica set primary before an exception occurs and task is aborted. defaults to 16, which with the defaults for connect.backoff.initial.delay.ms and connect.backoff.max.delay.msresults in just over 20 minutes of attempts before failing.

mongodb.members.auto.discover

true

boolean value that specifies whether the addresses in 'mongodb.hosts' are seeds that should be used to discover all members of the cluster or replica set (true), or whether the address(es) in mongodb.hosts should be used as is (false). the default is true and should be used in all cases except where mongodb is .

source.struct.version

v2

schema version for the source block in cdc events; debezium 0.10 introduced a few breaking
changes to the structure of the source block in order to unify the exposed structure across all the connectors.
by setting this option to v1 the structure used in earlier versions can be produced. note that this setting is not recommended and is planned for removal in a future debezium version.

heartbeat.interval.ms

0

controls how frequently heartbeat messages are sent.
this property contains an interval in milli-seconds that defines how frequently the connector sends messages into a heartbeat topic. this can be used to monitor whether the connector is still receiving change events from the database. you also should leverage heartbeat messages in cases where only records in non-captured collections are changed for a longer period of time. in such situation the connector would proceed to read the oplog from the database but never emit any change messages into kafka, which in turn means that no offset updates will be committed to kafka. this will cause the oplog files to be rotated out but connector will not notice it so on restart some events are no longer available which leads to the need of re-execution of the initial snapshot.

set this parameter to 0 to not send heartbeat messages at all.
disabled by default.

heartbeat.topics.prefix

__debezium-heartbeat

controls the naming of the topic to which heartbeat messages are sent.
the topic is named according to the pattern <heartbeat.topics.prefix>.<server.name>.

sanitize.field.names

true when connector configuration explicitly specifies the key.converter or value.converterparameters to use avro, otherwise defaults to false.

whether field names will be sanitized to adhere to avro naming requirements. see avro namingfor more details.

这里以standalone的模式运行,在connect-standalone.properties中做如下配置:

# 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
rest.port=9093
# 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=false
value.converter.schemas.enable=false
rest.host.name=0.0.0.0
offset.storage.file.filename=/data4/kafka/connect/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=/opt/kafka/kafka_2.11-2.0.0/plugin

standalone模式下启动方式如下:

bin/connect-standalone.sh config/connect-standalone.properties connector1.properties[connector2.properties ...]   一次可以启动多个connector,只需要在参数中加上connector的配置文件路径即可。

例如:connect-standalone.sh config/connect-standalone.properties mongodb.properties

distribute模式部署:

1、修改配置connect-distributed.properties

# broker列表
bootstrap.servers=10.120.241.1:9200
 
# 同一集群中group.id需要配置一致,且不能和别的消费者同名
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
# 使用json数据同样配置成false
key.converter.schemas.enable=false
value.converter.schemas.enable=false
····

2、手动创建集群模式所必须的kafka的几个topic

# config.storage.topic=connect-configs
$ bin/kafka-topics --create --zookeeper localhost:2181 --topic connect-configs --replication-factor 3 --partitions 1 --config cleanup.policy=compact
 
# offset.storage.topic=connect-offsets
$ bin/kafka-topics --create --zookeeper localhost:2181 --topic connect-offsets --replication-factor 3 --partitions 50 --config cleanup.policy=compact
 
# status.storage.topic=connect-status
$ $ bin/kafka-topics --create --zookeeper localhost:2181 --topic connect-status --replication-factor 3 --partitions 10 --config cleanup.policy=compact
  • config.storage.topic:topic用于存储connector和任务配置;注意,这应该是一个单个的partition,多副本的topic
  • offset.storage.topic:用于存储offsets;这个topic应该配置多个partition和副本。
  • status.storage.topic:用于存储状态;这个topic 可以有多个partitions和副本

3、 启动worker

启动distributed模式命令如下:

./bin/connect-distributed ./etc/kafka/connect-distributed.properties   

4、使用restful启动connect
curl 'http://localhost:8083/connectors' -x post -i -h "content-type:application/json" -d   
    '{ "name":"elasticsearch-sink",  
       "config":{"connector.class":"io.confluent.connect.elasticsearch.elasticsearchsinkconnector",  
                "tasks.max":10,  
                "topics":"estest1012",  
                "key.ignore":true,  
                "schema.ignore":true,  
                "connection.url":"http://10.120.241.194:9200",  
                "type.name":"kafka-connect"}  
    }' 

常见问题:

1、在启动的过程中出现各种各样的java.lang.classnotfoundexception。

在启动connector的时候,一开始总是会报各个各样的classnotfoundexception,不是这个包就是那个包,查找问题一直说要么缺少包要么是包冲突,那么要排除依赖冲突或者看下是不是少了jar包。

2、在connector.properties中的key.converter.schemas.enable=false和value.converter.schemas.enable=false的问题。

这个选项默认在connect-standalone.properties中是true的,这个时候发送给topic的json格式是需要使用avro格式。例如:
{
    "schema": {
        "type": "struct",
        "fields": [{
            "type": "int32",
            "optional": true,
            "field": "c1"
        }, {
            "type": "string",
            "optional": true,
            "field": "c2"
        }, {
            "type": "int64",
            "optional": false,
            "name": "org.apache.kafka.connect.data.timestamp",
            "version": 1,
            "field": "create_ts"
        }, {
            "type": "int64",
            "optional": false,
            "name": "org.apache.kafka.connect.data.timestamp",
            "version": 1,
            "field": "update_ts"
        }],
        "optional": false,
        "name": "foobar"
    },
    "payload": {
        "c1": 10000,
        "c2": "bar",
        "create_ts": 1501834166000,
        "update_ts": 1501834166000
    }
}

如果想发送普通的json格式而不是avro格式的话,很简单key.converter.schemas.enable和value.converter.schemas.enable设置为false就行。这样就能发送普通的json格式数据。