-
Notifications
You must be signed in to change notification settings - Fork 0
/
publisher.py
77 lines (58 loc) · 2.23 KB
/
publisher.py
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
import threading
from kafka import KafkaProducer, KafkaConsumer
from json import dumps, loads
from collections import namedtuple
data = namedtuple("news", ("title", "context"))
class Publisher():
def __init__(self, topic_name, buffer_size=16):
self.producer = KafkaProducer(bootstrap_servers=['localhost:9092'], value_serializer=lambda x: dumps(x).encode('utf-8'))
self.topic_name = topic_name
self.buffer_size = buffer_size
self.run_thread = None
self.stop = False
self.queue = []
self.run()
def publish(self, msg):
if len(self.queue) >= self.buffer_size:
del self.queue[0]
self.queue.append(msg)
def run(self):
self.run_thread = threading.Thread(target=self._run)
self.run_thread.start()
def close(self):
if self.run_thread is not None:
if self.stop is False:
self.stop = True
self.run_thread.join()
def stop(self):
self.stop = True
def _run(self):
while self.stop is False:
self.producer.poll(0)
if len(self.queue) > 0:
msg = self.queue.pop(0)
producer.produce(self.topic_name, f"{msg}".encode("utf-8"))
producer.flush()
print(f"[INFO] Producer produced at topic {self.topic_name}")
class KafkaHelper(object):
@classmethod
def _producer(cls):
return KafkaProducer(bootstrap_servers=['localhost:9092'], value_serializer=lambda x: dumps(x).encode('utf-8'))
@classmethod
def _consumer(cls, topic):
return KafkaConsumer(topic, bootstrap_servers=['localhost:9092'], value_deserializer=lambda x: loads(x.decode('utf8')))
@classmethod
def pub_noutput(cls, result):
return cls._producer().send("noutput", result)
@classmethod
def pub_foutput(cls, result):
return cls._producer().send("foutput", result)
# consume functions are blockable til new record come
@classmethod
def consume_ninput(cls):
record = next(iter(cls._consumer("ninput")))
return record.value
@classmethod
def consume_ninput(cls):
record = next(iter(cls._consumer("finput")))
return record.value