Python 消费Kafka手动提交 批量存入Elasticsearch

一、第三方包选择

pip install kafka ,对比了kafka和pykafka,还是选择kafka,消费速度更快
pip install elasticsearch==7.12.0(ES版本)

二、创建es连接对象

复制代码
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk

class Create_ES(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, hosts):
        try:
            self.es = Elasticsearch([{'host':host, 'port':9200}])
        except Exception as e:
            print('Connect ES Fail db:{} error:{}'.format(hosts, str(e)))

    def get_conn(self):
        return self.es

    def set_multi_data(self, datas):
        '''批量插入数据'''
        success = bulk(self.es, datas, raise_on_error=True)
        return success

三、消费kafka数据

复制代码
from kafka import KafkaConsumer, TopicPartition, OffsetAndMetadata
from . import Create_ES

class AppKfkConsumer(object):
    def __init__(self):
        self.server = 'localhost:9092'
        self.topic = KAFKA_TOPIC
        self.consumer = None
        self.tp = None
        self.consumer_timeout_ms = 5000  # 设置消费超时时间,
        self.type = 'members'
        self.group_id = 'test1'  # 设置消费group_id,避免重复消费
        self.es_index = 'index'  # es的index

    def get_connect(self):
        self.consumer = KafkaConsumer(
                                     group_id=self.group_id,
                                     auto_offset_reset='earliest',  # 从最早的数据开始消费
                                     bootstrap_servers=self.server,
                                     enable_auto_commit=False,  # 关闭自动提交
                                     consumer_timeout_ms=self.consumer_timeout_ms
                       )
        self.tp = TopicPartition(topic=self.topic, partition=0)  # 设置我们要消费的分区
        self.consumer.assign([self.tp])  # 由consumer对象分配分区

    def beginConsumer(self):
        now_offset = 0  # 当前偏移量
               
        es_conn = Create_ES()
        Actions = []
        while True:
            for message in self.consumer:
                now_offset = message.offset  # 获取当前偏移量
                data = eval(message.value.decode())  # 解析数据
                action = {
                    "_index": self.es_index,
                    "_type": self.type,
                    "_source": data
                }
                Actions.append(action)
                if len(Actions) >= 50000:
                    result = es_conn.set_multi_data(Actions)  # 批量插入数据
                    Actions = []
                    # 提交偏移量,now_offset+1的原因是因为我发现如果不加1,下次消费会从上次消费最后一条数据开始,重复消费
                    self.consumer.commit(offsets={tp:(OffsetAndMetadata(now_offset+1, None))})

            if len(Actions) > 0:
                result = es_conn.set_multi_data(Actions)
                Actions = []
                self.consumer.commit(offsets={tp:(OffsetAndMetadata(now_offset+1, None))})


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

# 执行任务
ks = AppKfkConsumer()
ks.get_connect()
ks.beginConsumer()
相关推荐
Dingdangcat8611 分钟前
反恐精英角色识别与定位-基于改进的boxinst_r101_fpn_ms-90k_coco模型实现
python
世界唯一最大变量28 分钟前
利用自定义积分公式,目前可以求出所有1元方程和1元积分的近似值
python
写代码的【黑咖啡】43 分钟前
深入理解 Python 中的模块(Module)
开发语言·python
爱笑的眼睛112 小时前
超越 `cross_val_score`:深度解析Scikit-learn交叉验证API的架构、技巧与陷阱
java·人工智能·python·ai
Wang's Blog2 小时前
Kafka: 消费者核心机制
分布式·kafka
smj2302_796826523 小时前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode
gCode Teacher 格码致知3 小时前
Python基础教学:Python 3中的字符串在解释运行时的内存编码表示-由Deepseek产生
python·内存编码
翔云 OCR API4 小时前
承兑汇票识别接口技术解析与应用实践
开发语言·人工智能·python·计算机视觉·ocr
likerhood4 小时前
3. pytorch中数据集加载和处理
人工智能·pytorch·python
Data_agent4 小时前
京东图片搜索商品API,json数据返回
数据库·python·json