-
Notifications
You must be signed in to change notification settings - Fork 0
/
customer_app.py
executable file
·61 lines (52 loc) · 2.67 KB
/
customer_app.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
from types import SimpleNamespace
import pika
import json
from db_and_event_definitions import CustomerEvent
import time
import logging
from xprint import xprint
class CustomerEventConsumer:
def __init__(self, customer_id):
# Do not edit the init method.
# Set the variables appropriately in the methods below.
self.customer_id = customer_id
self.connection = None
self.channel = None
self.temporary_queue_name = None
self.customer_events = []
self.customer_events_exchange = "customer_events_exchange"
def initialize_rabbitmq(self):
# To implement - Initialize the RabbitMq connection, channel, exchange and queue here
xprint("CustomerEventConsumer {}: initialize_rabbitmq() called".format(self.customer_id))
self.connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
self.channel = self.connection.channel()
self.channel.exchange_declare(exchange=self.customer_events_exchange, exchange_type='topic')
self.temporary_queue_name = self.channel.queue_declare(queue='', exclusive=True).method.queue
self.channel.queue_bind(exchange=self.customer_events_exchange, queue=self.temporary_queue_name, routing_key=self.customer_id)
self.channel.basic_consume(queue=self.temporary_queue_name, on_message_callback=self.handle_event, auto_ack=True)
def handle_event(self, ch, method, properties, body):
# To implement - This is the callback that is passed to "on_message_callback" when a message is received
xprint("CustomerEventConsumer {}: handle_event() called".format(self.customer_id))
# Handle the application logic here
customer_event = CustomerEvent(**json.loads(body))
self.customer_events.append(customer_event)
def start_consuming(self):
# To implement - Start consuming from Rabbit
xprint("CustomerEventConsumer {}: start_consuming() called".format(self.customer_id))
self.channel.basic_consume(queue=self.temporary_queue_name, on_message_callback=self.handle_event, auto_ack=True)
self.channel.start_consuming()
def close(self):
# Do not edit this method
try:
if self.channel is not None:
print("CustomerEventConsumer {}: Closing".format(self.customer_id))
self.channel.stop_consuming()
time.sleep(1)
self.channel.close()
if self.connection is not None:
self.connection.close()
except Exception as e:
print("CustomerEventConsumer {}: Exception {} on close()"
.format(self.customer_id, e))
pass