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实现封装得到virustotal扫描结果
Oct 05 Python
Python基于smtplib实现异步发送邮件服务
May 28 Python
Python中模块string.py详解
Mar 12 Python
python django使用haystack:全文检索的框架(实例讲解)
Sep 27 Python
使用apidocJs快速生成在线文档的实例讲解
Feb 07 Python
python3+PyQt5实现自定义流体混合窗口部件
Apr 24 Python
python2.7实现爬虫网页数据
May 25 Python
python mysql断开重连的实现方法
Jul 26 Python
使用Puppeteer爬取微信文章的实现
Feb 11 Python
使用python图形模块turtle库绘制樱花、玫瑰、圣诞树代码实例
Mar 16 Python
pyinstaller打包找不到文件的问题解决
Apr 15 Python
Pytorch 扩展Tensor维度、压缩Tensor维度的方法
Sep 09 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 获取客户端真实IP地址多种方法小结
2010/05/15 PHP
ThinkPHP使用心得分享-上传类UploadFile的使用
2014/05/15 PHP
如何使用php脚本给html中引用的js和css路径打上版本号
2015/11/18 PHP
论坛里点击别人帖子下面的回复,回复标题变成“回复 24# 的帖子”
2009/06/14 Javascript
JQuery扩展插件Validate 3通过参数设置错误信息
2011/09/05 Javascript
批量修改标签css样式以input标签为例
2014/07/31 Javascript
JavaScript sup方法入门实例(把字符串显示为上标)
2014/10/20 Javascript
JavaScript中判断数据类型的方法总结
2016/05/24 Javascript
如何在JS中实现相互转换XML和JSON
2016/07/19 Javascript
ng-options和ng-checked在表单中的高级运用(推荐)
2017/01/21 Javascript
jQuery实现简单弹窗遮罩效果
2017/02/27 Javascript
详解js创建对象的几种方法及继承
2019/04/12 Javascript
React+TypeScript+webpack4多入口配置详解
2019/08/08 Javascript
超简单的微信小程序轮播图
2019/11/22 Javascript
vue 开发企业微信整合案例分析
2019/12/02 Javascript
深入理解 ES6中的 Reflect用法
2020/07/18 Javascript
python中getattr函数使用方法 getattr实现工厂模式
2014/01/20 Python
十条建议帮你提高Python编程效率
2016/02/16 Python
教大家玩转Python字符串处理的七种技巧
2017/03/31 Python
Python3.5基础之变量、数据结构、条件和循环语句、break与continue语句实例详解
2019/04/26 Python
简单了解python关系(比较)运算符
2019/07/08 Python
实例讲解CSS3中的box-flex弹性盒属性布局
2016/06/09 HTML / CSS
HTML5去掉输入框type为number时的上下箭头的实现方法
2020/01/03 HTML / CSS
video下autoplay属性无效的解决方法(添加muted属性)
2020/05/19 HTML / CSS
Napapijri西班牙在线商店:夹克、外套、运动衫等
2020/11/05 全球购物
如何判断一段程序是由C 编译程序还是由C++编译程序编译的
2013/08/04 面试题
电子商务专业个人的自我评价
2013/11/19 职场文书
初中生物教学反思
2014/01/10 职场文书
文秘人员工作职责
2014/01/31 职场文书
《理想》教学反思
2014/02/17 职场文书
青春演讲稿范文
2014/05/08 职场文书
学校就业推荐信范文
2014/05/19 职场文书
2014年小学语文工作总结
2014/12/20 职场文书
大学生,三分钟即兴演讲稿
2019/07/22 职场文书
创业计划书之零食店(进口)
2019/09/24 职场文书
Python Pandas常用函数方法总结
2021/06/15 Python