python消费kafka数据批量插入到es的方法


Posted in Python onDecember 27, 2018

1、es的批量插入

这是为了方便后期配置的更改,把配置信息放在logging.conf中

用elasticsearch来实现批量操作,先安装依赖包,sudo pip install Elasticsearch2

from elasticsearch import Elasticsearch 
class ImportEsData:

  logging.config.fileConfig("logging.conf")
  logger = logging.getLogger("msg")

  def __init__(self,hosts,index,type):
    self.es = Elasticsearch(hosts=hosts.strip(',').split(','), timeout=5000)
    self.index = index
    self.type = type


  def set_date(self,data): 
    # 批量处理 
    # es.index(index="test-index",doc_type="test-type",id=42,body={"any":"data","timestamp":datetime.now()})
    self.es.index(index=self.index,doc_type=self.index,body=data)

2、使用pykafka消费kafka

1.因为kafka是0.8,pykafka不支持zk,只能用get_simple_consumer来实现

2.为了实现多个应用同时消费而且不重消费,所以一个应用消费一个partition

3. 为是确保消费数据量在不满足10000这个批量值,能在一个时间范围内插入到es中,这里设置consumer_timeout_ms一个超时等待时间,退出等待消费阻塞。

4.退出等待消费阻塞后导致无法再消费数据,因此在获取self.consumer 的外层加入了while True 一个死循环

#!/usr/bin/python
# -*- coding: UTF-8 -*-
from pykafka import KafkaClient
import logging
import logging.config
from ConfigUtil import ConfigUtil
import datetime


class KafkaPython:
  logging.config.fileConfig("logging.conf")
  logger = logging.getLogger("msg")
  logger_data = logging.getLogger("data")

  def __init__(self):
    self.server = ConfigUtil().get("kafka","kafka_server")
    self.topic = ConfigUtil().get("kafka","topic")
    self.group = ConfigUtil().get("kafka","group")
    self.partition_id = int(ConfigUtil().get("kafka","partition"))
    self.consumer_timeout_ms = int(ConfigUtil().get("kafka","consumer_timeout_ms"))
    self.consumer = None
    self.hosts = ConfigUtil().get("es","hosts")
    self.index_name = ConfigUtil().get("es","index_name")
    self.type_name = ConfigUtil().get("es","type_name")


  def getConnect(self):
    client = KafkaClient(self.server)
    topic = client.topics[self.topic]
    p = topic.partitions
    ps={p.get(self.partition_id)}

    self.consumer = topic.get_simple_consumer(
      consumer_group=self.group,
      auto_commit_enable=True,
      consumer_timeout_ms=self.consumer_timeout_ms,
      # num_consumer_fetchers=1,
      # consumer_id='test1',
      partitions=ps
      )
    self.starttime = datetime.datetime.now()


  def beginConsumer(self):
    print("beginConsumer kafka-python")
    imprtEsData = ImportEsData(self.hosts,self.index_name,self.type_name)
    #创建ACTIONS 
    count = 0
    ACTIONS = [] 

    while True:
      endtime = datetime.datetime.now()
      print (endtime - self.starttime).seconds
      for message in self.consumer:
        if message is not None:
          try:
            count = count + 1
            # print(str(message.partition.id)+","+str(message.offset)+","+str(count))
            # self.logger.info(str(message.partition.id)+","+str(message.offset)+","+str(count))
            action = { 
              "_index": self.index_name, 
              "_type": self.type_name, 
              "_source": message.value
            }
            ACTIONS.append(action)
            if len(ACTIONS) >= 10000:
              imprtEsData.set_date(ACTIONS)
              ACTIONS = []
              self.consumer.commit_offsets()
              endtime = datetime.datetime.now()
              print (endtime - self.starttime).seconds
              #break
          except (Exception) as e:
            # self.consumer.commit_offsets()
            print(e)
            self.logger.error(e)
            self.logger.error(str(message.partition.id)+","+str(message.offset)+","+message.value+"\n")
            # self.logger_data.error(message.value+"\n")
          # self.consumer.commit_offsets()


      if len(ACTIONS) > 0:
        self.logger.info("等待时间超过,consumer_timeout_ms,把集合数据插入es")
        imprtEsData.set_date(ACTIONS)
        ACTIONS = []
        self.consumer.commit_offsets()




  def disConnect(self):
    self.consumer.close()


from elasticsearch import Elasticsearch 
from elasticsearch.helpers import bulk
class ImportEsData:

  logging.config.fileConfig("logging.conf")
  logger = logging.getLogger("msg")

  def __init__(self,hosts,index,type):
    self.es = Elasticsearch(hosts=hosts.strip(',').split(','), timeout=5000)
    self.index = index
    self.type = type


  def set_date(self,data): 
    # 批量处理 
    success = bulk(self.es, data, index=self.index, raise_on_error=True) 
    self.logger.info(success)

3、运行

if __name__ == '__main__':
  kp = KafkaPython()
  kp.getConnect()
  kp.beginConsumer()
  # kp.disConnect()

注:简单的写了一个从kafka中读取数据到一个list里,当数据达到一个阈值时,在批量插入到 es的插件

现在还在批量的压测中。。。

以上这篇python消费kafka数据批量插入到es的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python设置windows桌面壁纸的实现代码
Jan 28 Python
使用Python的内建模块collections的教程
Apr 28 Python
python基于隐马尔可夫模型实现中文拼音输入
Apr 01 Python
详解Python中heapq模块的用法
Jun 28 Python
python中利用队列asyncio.Queue进行通讯详解
Sep 10 Python
Python编程给numpy矩阵添加一列方法示例
Dec 04 Python
Python如何处理大数据?3个技巧效率提升攻略(推荐)
Apr 15 Python
20行python代码的入门级小游戏的详解
May 05 Python
python射线法判断一个点在图形区域内外
Jun 28 Python
TensorFlow2.0矩阵与向量的加减乘实例
Feb 07 Python
Python办公自动化之教你用Python批量识别发票并录入到Excel表格中
Jun 26 Python
如何Python使用re模块实现okenizer
Apr 30 Python
Python通过paramiko远程下载Linux服务器上的文件实例
Dec 27 #Python
Python基于Tkinter模块实现的弹球小游戏
Dec 27 #Python
python 读取Linux服务器上的文件方法
Dec 27 #Python
Python 脚本获取ES 存储容量的实例
Dec 27 #Python
Python数据结构之栈、队列及二叉树定义与用法浅析
Dec 27 #Python
python获取本机所有IP地址的方法
Dec 26 #Python
python检测IP地址变化并触发事件
Dec 26 #Python
You might like
php中获得视频时间总长度的另一种方法
2011/09/15 PHP
PHP解耦的三重境界(浅谈服务容器)
2017/03/13 PHP
PHP实现文件下载【实例分享】
2017/04/28 PHP
用jscript实现列出安装的软件列表
2007/06/18 Javascript
IE7中javascript操作CheckBox的checked=true不打勾的解决方法
2009/12/07 Javascript
小巧强大的jquery layer弹窗弹层插件
2015/12/06 Javascript
js实现文字垂直滚动和鼠标悬停效果
2015/12/31 Javascript
js实现加载更多功能实例
2016/10/27 Javascript
Angular.JS内置服务$http对数据库的增删改使用教程
2017/05/07 Javascript
Vue中的Props(不可变状态)
2018/09/29 Javascript
微信小程序实现工作时间段选择
2019/02/15 Javascript
jQuery实现简单评论功能
2020/08/19 jQuery
[01:24:34]2014 DOTA2华西杯精英邀请赛5 24 DK VS LGD
2014/05/25 DOTA
[00:12]2018DOTA2亚洲邀请赛 sylar表现SOLO技艺
2018/04/06 DOTA
python多线程编程中的join函数使用心得
2014/09/02 Python
django中静态文件配置static的方法
2018/05/20 Python
由面试题加深对Django的认识理解
2019/07/19 Python
python修改字典键(key)的方法
2019/08/05 Python
django 通过url实现简单的权限控制的例子
2019/08/16 Python
python使用 cx_Oracle 模块进行查询操作示例
2019/11/28 Python
Python多线程实现支付模拟请求过程解析
2020/04/21 Python
HTML5响应式(自适应)网页设计的实现
2017/11/17 HTML / CSS
日本酒店、民宿、温泉旅馆、当地旅行团中文预订:e路东瀛
2019/12/09 全球购物
新东方旗下远程教育网站:新东方在线
2020/03/19 全球购物
Herschel Supply Co.美国:背包、手提袋及配件
2020/11/24 全球购物
2014年扫黄打非工作总结
2014/12/03 职场文书
出租车拒载检讨书
2015/01/28 职场文书
违纪学生保证书
2015/02/27 职场文书
员工工作表扬信
2015/05/05 职场文书
2015年社区宣传工作总结
2015/05/20 职场文书
2015年度企业工作总结
2015/05/21 职场文书
安全生产奖惩制度
2015/08/06 职场文书
Python使用mitmproxy工具监控手机 下载手机小视频
2022/04/18 Python
Python实现对齐打印 format函数的用法
2022/04/28 Python
MySQL的prepare使用以及遇到的bug
2022/05/11 MySQL
CSS中使用grid布局实现一套模板多种布局
2022/07/15 HTML / CSS