1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
| import kafka import time import datetime import uuid from queue import Queue
class KafkaProducer(kafka.KafkaProducer): def __init__(self, server): super().__init__( bootstrap_servers=[server], api_version=(2,3,1), api_version_auto_timeout_ms=5000 )
def send(self, topic, key, data): assert(isinstance(data, bytes)) timestamp = "{}{}".format(datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3], uuid.uuid4().hex[:15]) timestamp = timestamp[:32] value = timestamp.encode() + data return super().send(topic, key=key.encode(), value=value)
class KafkaConsumer(kafka.KafkaConsumer): def __init__(self, server, group_id=None): super().__init__( bootstrap_servers=[server], group_id=group_id, auto_offset_reset='latest', enable_auto_commit=True, api_version=(2,3,1), api_version_auto_timeout_ms=5000 ) self.server = server self.q = Queue() self.s = set() self.DUP_DETECT_SIZE = 1000
def subscribe(self, topic): if topic not in super().topics(): producer = kafka.KafkaProducer( bootstrap_servers=[self.server], api_version=(2,3,1), api_version_auto_timeout_ms=5000 ) producer.send(topic, key=b"", value=b"") producer.flush() super().subscribe(topic)
def subscribe_from_datetime(self, topic, dt): if topic not in super().topics(): producer = kafka.KafkaProducer( bootstrap_servers=[self.server], api_version=(2,3,1), api_version_auto_timeout_ms=5000 ) producer.send(topic, key=b"", value=b"") producer.flush() if type(dt) is int or type(dt) is float: ts = dt elif isinstance(dt, datetime.datetime): ts = dt.timestamp() else: ts = time.mktime(time.strptime(f"{dt}", r"%Y-%m-%d %H:%M:%S")) offset = self._get_offset_for_time(topic, ts) partition = 0 tp = kafka.TopicPartition(topic, partition) super().assign([tp]) super().seek(tp, offset)
def __iter__(self): return self
def __next__(self): while True: message = super().__next__() msg_type = message.key if not msg_type or len(message.value) < 32: continue timestamp = message.value[:32].decode() if timestamp in self.s: continue if len(self.s) >= self.DUP_DETECT_SIZE: e = self.q.get() self.s.remove(e) self.s.add(timestamp) self.q.put(timestamp)
data = message.value[32:] return (msg_type.decode(), data, timestamp)
def get_messages(self, max_records=20): r = super().poll(timeout_ms=max_records*25, max_records=max_records) ret = [] for messages in r.values(): for message in messages: msg_type = message.key if not msg_type or len(message.value) < 32: continue timestamp = message.value[:32].decode() if timestamp in self.s: continue if len(self.s) >= self.DUP_DETECT_SIZE: e = self.q.get() self.s.remove(e) self.s.add(timestamp) self.q.put(timestamp)
data = message.value[32:] ret.append((msg_type.decode(), data, timestamp)) return ret
def _get_latest_offset(self, topic): partition = 0 tp = kafka.TopicPartition(topic, partition) super().assign([tp]) off_set_dict = super().end_offsets([tp]) return list(off_set_dict.values())[0]
def _get_offset_for_time(self, topic, ts): partition = 0 tp = kafka.TopicPartition(topic, partition) super().assign([tp]) offset_dict = super().offsets_for_times({tp: int(ts*1000)}) offset = list(offset_dict.values())[0] if offset is None: return self.get_latest_offset(topic) else: return offset.offset
|