Last active
March 28, 2021 13:17
-
-
Save hzbd/a1b80a918fea56128d97831bbcf1e858 to your computer and use it in GitHub Desktop.
kafka python3 handler kit.(writer&reader&admin)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# | |
# Copyright (c) 2021 六二三 | |
# Licensed under the MIT License. | |
# All rights reserved. | |
# | |
# Deps: | |
# pip3 install kafka-python==2.0.2 | |
# | |
# | |
from kafka import KafkaConsumer | |
from kafka import KafkaProducer | |
from kafka.errors import KafkaError, KafkaTimeoutError, TopicAlreadyExistsError, UnknownTopicOrPartitionError | |
from kafka import KafkaAdminClient | |
from kafka import OffsetAndMetadata | |
from kafka.structs import TopicPartition | |
from kafka.admin import NewTopic | |
import json | |
import logging | |
logger = logging.getLogger(__name__) | |
class KafkaHandler(object): | |
""" Kafka Handler""" | |
def __init__(self, bootstrap_servers='localhost:9092'): | |
self.kafka_admin = KafkaAdminClient(bootstrap_servers=bootstrap_servers) | |
def create_topic(self, topic_name, partitions=1, replication_factor=1): | |
try: | |
topic = NewTopic(name=topic_name, num_partitions=partitions, replication_factor=replication_factor) | |
self.kafka_admin.create_topics([topic]) | |
return True | |
except (TopicAlreadyExistsError, Exception): | |
logger.error("create kafka topic({}) failed".format(topic_name)) | |
return False | |
def delete_topic(self, topic_name): | |
try: | |
self.kafka_admin.delete_topics([topic_name]) | |
return True | |
except (UnknownTopicOrPartitionError, Exception): | |
logger.error("delete kafka topic({}) failed".format(topic_name)) | |
return False | |
def close(self): | |
self.kafka_admin.close() | |
class KafkaWriter(object): | |
""" Kafka Producer""" | |
def __init__(self, bootstrap_servers=['localhost:9092']): | |
self.producer = KafkaProducer( | |
bootstrap_servers=bootstrap_servers, | |
retries=1, | |
value_serializer=lambda v: json.dumps(v).encode('utf-8'), | |
compression_type='gzip') | |
def send(self, topic, message={}): | |
try: | |
self.producer.send(topic, message) | |
# print(self.producer.metrics()) | |
except KafkaTimeoutError as timeout_error: | |
print(timeout_error.message) | |
except KafkaError as kafka_error: | |
print(kafka_error.message) | |
except Exception as error: | |
print(error) | |
def close(self): | |
self.producer.close() | |
class KafkaReader(object): | |
""" Kafka Consumer""" | |
def __init__( | |
self, | |
bootstrap_servers=['localhost:9092'], | |
timeout=1000, | |
group_id="kafka_reader"): | |
self.consumer = KafkaConsumer( | |
bootstrap_servers=bootstrap_servers, | |
group_id=group_id, | |
value_deserializer=lambda m: json.loads(m.decode('utf8')), | |
consumer_timeout_ms=timeout, | |
auto_offset_reset='earliest', | |
enable_auto_commit=True, | |
max_poll_records=10) | |
def topic_list(self): | |
return self.consumer.topics() | |
def start(self, topic="test-topic", limit=100): | |
message_list = [] | |
self.consumer.subscribe([topic]) | |
# self.consumer.subscribe(pattern='^awesome.*') | |
partitions = self.consumer.partitions_for_topic(topic) | |
if not partitions: | |
return | |
for partition in partitions: | |
topic_partition = TopicPartition(topic=topic, partition=partition) | |
# current_offset = self.consumer.end_offsets([topic_partition])[topic_partition] | |
# self.consumer.seek(partition=topic_partition, offset=current_offset) | |
messages = self.consumer.poll(timeout_ms=1000, max_records=limit) | |
for _, messages in messages.items(): | |
for message in messages: | |
logger.debug("{} | {} | {}".format(message.topic, message.value, message.offset)) | |
message_list.append( | |
{ | |
"topic": message.topic, | |
"value": message.value, | |
"offset": message.offset | |
} | |
) | |
self.consumer.commit(offsets={topic_partition: (OffsetAndMetadata(message.offset, None))}) | |
self.consumer.close() | |
return message_list | |
if __name__ == '__main__': | |
# kh = KafkaHandler() | |
# kh.create_topic("test-4", partitions=4) | |
# worker = KafkaReader() | |
# print(worker.topic_list()) | |
topic = "demo-130" | |
# for i in range(50): | |
# print("sending...") | |
# json_data = {'foo': 'bar', 'gooood': i} | |
# kw = KafkaWriter() | |
# kw.send(topic, json_data) | |
# kw.close() | |
kr = KafkaReader() | |
ret = kr.start(topic=topic, limit=10) | |
for v in ret: | |
print(v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to quickly start a local Kafka cluster
Starting CMAK service