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实现的解析crontab配置文件代码
Jun 30 Python
Python编程中实现迭代器的一些技巧小结
Jun 21 Python
Python lambda函数基本用法实例分析
Mar 16 Python
Pycharm2017版本设置启动时默认自动打开项目的方法
Oct 29 Python
python将list转为matrix的方法
Dec 12 Python
Python redis操作实例分析【连接、管道、发布和订阅等】
May 16 Python
Python3 实现文件批量重命名示例代码
Jun 03 Python
TensorFlow索引与切片的实现方法
Nov 20 Python
Python @property及getter setter原理详解
Mar 31 Python
tensorflow 20:搭网络,导出模型,运行模型的实例
May 26 Python
Django项目如何获得SSL证书与配置HTTPS
Apr 30 Python
Python实现socket库网络通信套接字
Jun 04 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处理图片变得简单 基于gb库的图片处理类附实例代码下载
2011/05/17 PHP
PHP递归算法的详细示例分析
2013/02/19 PHP
PHP生成随机数的方法实例分析
2015/01/22 PHP
thinkphp微信开之安全模式消息加密解密不成功的解决办法
2015/12/02 PHP
简单实用的PHP文本缓存类实例
2019/03/22 PHP
精通Javascript系列之数值计算
2011/06/07 Javascript
jquery 查找iframe父级页面元素的实现代码
2011/08/28 Javascript
DOM2非标准但却支持很好的几个属性小结
2012/01/21 Javascript
IE的事件传递-event.cancelBubble示例介绍
2014/01/12 Javascript
NodeJS Express框架中处理404页面一个方式
2014/05/28 NodeJs
js点击返回跳转到指定页面实现过程
2020/08/20 Javascript
js 点击a标签 获取a的自定义属性方法
2016/11/21 Javascript
Nodejs+Socket.io实现通讯实例代码
2017/02/13 NodeJs
基于 D3.js 绘制动态进度条的实例详解
2018/02/26 Javascript
详解VUE里子组件如何获取父组件动态变化的值
2018/12/26 Javascript
微信小程序 image组件遇到的问题
2019/05/28 Javascript
最简单的vue消息提示全局组件的方法
2019/06/16 Javascript
[02:50]【扭转乾坤,只此一招】DOTA2全新版本永雾林渊开启新篇章
2020/12/24 DOTA
python中enumerate的用法实例解析
2014/08/18 Python
Python使用django获取用户IP地址的方法
2015/05/11 Python
python字典基本操作实例分析
2015/07/11 Python
Python通过90行代码搭建一个音乐搜索工具
2015/07/29 Python
使用python实现rsa算法代码
2016/02/17 Python
网站渗透常用Python小脚本查询同ip网站
2017/05/08 Python
Django框架教程之正则表达式URL误区详解
2018/01/28 Python
Python学习笔记之文件的读写操作实例分析
2019/08/07 Python
Pytorch中的variable, tensor与numpy相互转化的方法
2019/10/10 Python
Python定时从Mysql提取数据存入Redis的实现
2020/05/03 Python
python实现杨辉三角的几种方法代码实例
2021/03/02 Python
澳大利亚便宜隐形眼镜购买网站:QUICKLENS Australia
2018/10/06 全球购物
Hotels.com英国:全球领先的酒店住宿提供商
2019/01/24 全球购物
网络技术支持面试题
2013/04/22 面试题
餐饮企业总经理岗位职责范文
2014/02/18 职场文书
个人求职信范文
2014/05/24 职场文书
2015年小学语文工作总结
2015/05/25 职场文书
运动员加油词
2015/07/18 职场文书