pyspark流提交提交偏移到kafka

时间:2018-06-19 14:31:31

标签: python apache-spark apache-kafka spark-streaming

根据文档,可以从(scala)spark流应用程序中commit offset into kafka。 我想从pyspark实现相同的功能。
或至少将kafka分区存储到外部数据存储区(RDBMS等)中。

但是,用于kafka集成的pyspark api仅提供RDD(offset, value)]而不是RDD[ConsumerRecord](如在scala中)。 有什么方法可以从python RDD获取(topic, partition, offset)吗?并坚持到其他地方吗?

1 个答案:

答案 0 :(得分:0)

我们可以以多种方式处理偏移量。在每一个成功处理的数据中,我们可以在Zookeeper路径中存储Offset值并在再次创建流时读取该值的一种方法。代码片段如下。

from kazoo.client import KazooClient
zk = KazooClient(hosts='127.0.0.1:2181')
zk.start()
ZOOKEEPER_SERVERS = "127.0.0.1:2181"

def get_zookeeper_instance():
    from kazoo.client import KazooClient
    if 'KazooSingletonInstance' not in globals():
        globals()['KazooSingletonInstance'] = KazooClient(ZOOKEEPER_SERVERS)
        globals()['KazooSingletonInstance'].start()
    return globals()['KazooSingletonInstance']

def save_offsets(rdd):
    zk = get_zookeeper_instance()
    for offset in rdd.offsetRanges():
        path = f"/consumers/{var_topic_src_name}"
        print(path)
        zk.ensure_path(path)
        zk.set(path, str(offset.untilOffset).encode())

    var_offset_path = f'/consumers/{var_topic_src_name}'

    try:
        var_offset = int(zk.get(var_offset_path)[0])
    except:
        print("The spark streaming started First Time and Offset value should be Zero")
        var_offset  = 0
    var_partition = 0
    enter code here
    topicpartion = TopicAndPartition(var_topic_src_name, var_partition)
    fromoffset = {topicpartion: var_offset}
    print(fromoffset)
    kvs = KafkaUtils.createDirectStream(ssc,\
                                        [var_topic_src_name],\
                                        var_kafka_parms_src,\
                                        valueDecoder=serializer.decode_message,\
                                        fromOffsets = fromoffset)
    kvs.foreachRDD(handler)
    kvs.foreachRDD(save_offsets)

致谢

Karthikeyan Rasipalayam Durairaj