最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python 消費(fèi) kafka 數(shù)據(jù)教程

 更新時(shí)間:2019年12月21日 15:18:46   作者:bigdataf  
今天小編就為大家分享一篇python 消費(fèi) kafka 數(shù)據(jù)教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

1.安裝python模塊

pip install --user kafka-python==1.4.3 

如果報(bào)錯(cuò)壓縮相關(guān)的錯(cuò)嘗試安裝下面的依賴

yum install snappy-devel
yum install lz4-devel
pip install python-snappy
pip install lz4

2.生產(chǎn)者

#!/usr/bin/env python
# coding : utf-8

from kafka import KafkaProducer
import json

def kafkaProducer():
  producer = KafkaProducer(bootstrap_servers='ip:9092',value_serializer=lambda v: json.dumps(v).encode('utf-8'))
  producer.send('world', {'key1': 'value1'})

if __name__ == '__main__':
  kafkaProducer()

2.消費(fèi)者

from kafka import KafkaConsumer
from kafka.structs import TopicPartition
import time
import click
import ConfigParser
import json
import threading
import datetime
import sched


config = ConfigParser.ConfigParser()
config.read("amon.ini")

@click.group()
def cli():
  pass

@cli.command()
@click.option('--topic',type=str)
@click.option('--offset', type=click.Choice(['smallest', 'earliest', 'largest']))
@click.option("--group",type=str)
def client(topic,offset,group):
  click.echo(topic)
  consumer = KafkaConsumer(topic,
               bootstrap_servers=config.get("KAFKA", "Broker_Servers").split(","),
               group_id=group,
               auto_offset_reset=offset)
  for message in consumer:
    click.echo(message.value)
    # click.echo("%d:%d: key=%s value=%s" % (message.partition,
    #                      message.offset, message.key,
    #                      message.value))

if __name__ == '__main__':
  cli()

3.多線程消費(fèi)

#coding:utf-8
import threading

import os
import sys
from kafka import KafkaConsumer, TopicPartition, OffsetAndMetadata
from collections import OrderedDict


threads = []


class MyThread(threading.Thread):
  def __init__(self, thread_name, topic, partition):
    threading.Thread.__init__(self)
    self.thread_name = thread_name
    self.partition = partition
    self.topic = topic

  def run(self):
    print("Starting " + self.name)
    Consumer(self.thread_name, self.topic, self.partition)

  def stop(self):
    sys.exit()


def Consumer(thread_name, topic, partition):
  broker_list = 'ip1:9092,ip2:9092'

  '''
  fetch_min_bytes(int) - 服務(wù)器為獲取請(qǐng)求而返回的最小數(shù)據(jù)量,否則請(qǐng)等待
  fetch_max_wait_ms(int) - 如果沒(méi)有足夠的數(shù)據(jù)立即滿足fetch_min_bytes給出的要求,服務(wù)器在回應(yīng)提取請(qǐng)求之前將阻塞的最大時(shí)間量(以毫秒為單位)
  fetch_max_bytes(int) - 服務(wù)器應(yīng)為獲取請(qǐng)求返回的最大數(shù)據(jù)量。這不是絕對(duì)最大值,如果獲取的第一個(gè)非空分區(qū)中的第一條消息大于此值,
              則仍將返回消息以確保消費(fèi)者可以取得進(jìn)展。注意:使用者并行執(zhí)行對(duì)多個(gè)代理的提取,因此內(nèi)存使用將取決于包含該主題分區(qū)的代理的數(shù)量。
              支持的Kafka版本> = 0.10.1.0。默認(rèn)值:52428800(50 MB)。
  enable_auto_commit(bool) - 如果為True,則消費(fèi)者的偏移量將在后臺(tái)定期提交。默認(rèn)值:True。
  max_poll_records(int) - 單次調(diào)用中返回的最大記錄數(shù)poll()。默認(rèn)值:500
  max_poll_interval_ms(int) - poll()使用使用者組管理時(shí)的調(diào)用之間的最大延遲 。這為消費(fèi)者在獲取更多記錄之前可以閑置的時(shí)間量設(shè)置了上限。
                如果 poll()在此超時(shí)到期之前未調(diào)用,則認(rèn)為使用者失敗,并且該組將重新平衡以便將分區(qū)重新分配給另一個(gè)成員。默認(rèn)300000
  '''

  consumer = KafkaConsumer(bootstrap_servers=broker_list,
               group_id="test000001",
               client_id=thread_name,
               enable_auto_commit=False,
               fetch_min_bytes=1024 * 1024, # 1M
               # fetch_max_bytes=1024 * 1024 * 1024 * 10,
               fetch_max_wait_ms=60000, # 30s
               request_timeout_ms=305000,
               # consumer_timeout_ms=1,
               # max_poll_records=5000,
               )
  # 設(shè)置topic partition
  tp = TopicPartition(topic, partition)
  # 分配該消費(fèi)者的TopicPartition,也就是topic和partition,根據(jù)參數(shù),每個(gè)線程消費(fèi)者消費(fèi)一個(gè)分區(qū)
  consumer.assign([tp])
  #獲取上次消費(fèi)的最大偏移量
  offset = consumer.end_offsets([tp])[tp]
  print(thread_name, tp, offset)

  # 設(shè)置消費(fèi)的偏移量
  consumer.seek(tp, offset)

  print u"程序首次運(yùn)行\(zhòng)t線程:", thread_name, u"分區(qū):", partition, u"偏移量:", offset, u"\t開(kāi)始消費(fèi)..."
  num = 0 # 記錄該消費(fèi)者消費(fèi)次數(shù)
  while True:
    msg = consumer.poll(timeout_ms=60000)
    end_offset = consumer.end_offsets([tp])[tp]
    '''可以自己記錄控制消費(fèi)'''
    print u'已保存的偏移量', consumer.committed(tp), u'最新偏移量,', end_offset
    if len(msg) > 0:
      print u"線程:", thread_name, u"分區(qū):", partition, u"最大偏移量:", end_offset, u"有無(wú)數(shù)據(jù),", len(msg)
      lines = 0
      for data in msg.values():
        for line in data:
          print line
          lines += 1
        '''
        do something
        '''
      # 線程此批次消息條數(shù)

      print(thread_name, "lines", lines)
      if True:
        # 可以自己保存在各topic, partition的偏移量
        # 手動(dòng)提交偏移量 offsets格式:{TopicPartition:OffsetAndMetadata(offset_num,None)}
        consumer.commit(offsets={tp: (OffsetAndMetadata(end_offset, None))})
        if True == 0:
          # 系統(tǒng)退出?這個(gè)還沒(méi)試
          os.exit()
          '''
          sys.exit()  只能退出該線程,也就是說(shuō)其它兩個(gè)線程正常運(yùn)行,主程序不退出
          '''
      else:
        os.exit()
    else:
      print thread_name, '沒(méi)有數(shù)據(jù)'
    num += 1
    print thread_name, "第", num, "次"


if __name__ == '__main__':
  try:
    t1 = MyThread("Thread-0", "test", 0)
    threads.append(t1)
    t2 = MyThread("Thread-1", "test", 1)
    threads.append(t2)
    t3 = MyThread("Thread-2", "test", 2)
    threads.append(t3)

    for t in threads:
      t.start()

    for t in threads:
      t.join()

    print("exit program with 0")
  except:
    print("Error: failed to run consumer program")

參考:https://kafka-python.readthedocs.io/en/master/index.html

http://m.fzitv.net/article/176911.htm

以上這篇python 消費(fèi) kafka 數(shù)據(jù)教程就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python 用opencv實(shí)現(xiàn)圖像修復(fù)和圖像金字塔

    python 用opencv實(shí)現(xiàn)圖像修復(fù)和圖像金字塔

    這篇文章主要介紹了python 如何用opencv實(shí)現(xiàn)圖像修復(fù)和圖像金字塔,幫助大家更好的理解和使用python處理圖片,感興趣的朋友可以了解下
    2020-11-11
  • Pytorch使用技巧之Dataloader中的collate_fn參數(shù)詳析

    Pytorch使用技巧之Dataloader中的collate_fn參數(shù)詳析

    collate_fn 參數(shù)的目的主要是為了隨心所欲的轉(zhuǎn)變數(shù)據(jù)的類型,這個(gè)數(shù)據(jù)是用DataLoader加載的,比如img,target,下面這篇文章主要給大家介紹了關(guān)于Pytorch使用技巧之Dataloader中的collate_fn參數(shù)的相關(guān)資料,需要的朋友可以參考下
    2022-03-03
  • python優(yōu)化數(shù)據(jù)預(yù)處理方法Pandas pipe詳解

    python優(yōu)化數(shù)據(jù)預(yù)處理方法Pandas pipe詳解

    在本文中,我們將重點(diǎn)討論一個(gè)將多個(gè)預(yù)處理操作組織成單個(gè)操作的特定函數(shù):pipe。我將通過(guò)示例方式來(lái)展示如何使用它,讓我們從數(shù)據(jù)創(chuàng)建數(shù)據(jù)幀開(kāi)始吧
    2021-11-11
  • Python?pandas修剪函數(shù)clip使用實(shí)例探究

    Python?pandas修剪函數(shù)clip使用實(shí)例探究

    在數(shù)據(jù)處理和分析中,經(jīng)常面臨著需要限制數(shù)據(jù)范圍的情況,而pandas庫(kù)提供的clip函數(shù)就是一個(gè)強(qiáng)大的工具,可以方便地對(duì)數(shù)據(jù)進(jìn)行修剪,本文將深入介紹clip函數(shù)的基本用法、常見(jiàn)參數(shù)以及實(shí)際場(chǎng)景中的應(yīng)用,以幫助大家充分理解并靈活運(yùn)用這一功能
    2024-01-01
  • pandas數(shù)據(jù)清洗實(shí)現(xiàn)刪除的項(xiàng)目實(shí)踐

    pandas數(shù)據(jù)清洗實(shí)現(xiàn)刪除的項(xiàng)目實(shí)踐

    本文主要介紹了pandas數(shù)據(jù)清洗實(shí)現(xiàn)刪除的項(xiàng)目實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • 好的Python培訓(xùn)機(jī)構(gòu)應(yīng)該具備哪些條件

    好的Python培訓(xùn)機(jī)構(gòu)應(yīng)該具備哪些條件

    python是現(xiàn)在開(kāi)發(fā)的熱潮,大家應(yīng)該如何學(xué)習(xí)呢?許多人選擇自學(xué),還有人會(huì)選擇去培訓(xùn)結(jié)構(gòu)學(xué)習(xí),那么好的培訓(xùn)機(jī)構(gòu)的標(biāo)準(zhǔn)是什么樣的呢?下面跟隨腳本之家小編一起通過(guò)本文學(xué)習(xí)吧
    2018-05-05
  • Linux下python3.7.0安裝教程

    Linux下python3.7.0安裝教程

    這篇文章主要為大家詳細(xì)介紹了Linux下python3.7.0安裝教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • 老生常談進(jìn)程線程協(xié)程那些事兒

    老生常談進(jìn)程線程協(xié)程那些事兒

    下面小編就為大家?guī)?lái)一篇老生常談進(jìn)程線程協(xié)程那些事兒。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-07-07
  • python與pycharm有何區(qū)別

    python與pycharm有何區(qū)別

    在本篇文章里小編給大家整理了關(guān)于pycharm與python的區(qū)別相關(guān)內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。
    2020-07-07
  • python跳過(guò)第一行快速讀取文件內(nèi)容的實(shí)例

    python跳過(guò)第一行快速讀取文件內(nèi)容的實(shí)例

    今天小編就為大家分享一篇python跳過(guò)第一行快速讀取文件內(nèi)容的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-07-07

最新評(píng)論

慈溪市| 灵川县| 临夏县| 雅安市| 浦北县| 报价| 象州县| 梁平县| 长沙县| 德庆县| 香格里拉县| 忻州市| 夏邑县| 威海市| 东台市| 峡江县| 锡林浩特市| 曲阳县| 榕江县| 仙桃市| 博爱县| 辽中县| 黄龙县| 济宁市| 视频| 皮山县| 黄梅县| 临江市| 尉氏县| 克什克腾旗| 抚顺县| 利川市| 托里县| 丰城市| 金堂县| 凉山| 桐柏县| 曲麻莱县| 富蕴县| 依安县| 冷水江市|