Skip to content

Commit a408a2c

Browse files
committed
9: Refactor AMQP operation into separate thread.
1 parent 2f2a835 commit a408a2c

File tree

3 files changed

+31
-11
lines changed

3 files changed

+31
-11
lines changed

pyproject.toml

+9
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ dependencies = [
2828
"psycopg2-binary==2.9.7",
2929
]
3030

31+
[project.optional-dependencies]
32+
dev = [
33+
"setuptools-git-versioning<2",
34+
"pip-tools",
35+
"build",
36+
"setuptools"
37+
]
38+
39+
3140
[project.urls]
3241
"Homepage" = "https://github.com/pypa/sampleproject"
3342
"Bug Tracker" = "https://github.com/pypa/sampleproject/issues"

src/nwnsdk/nwn_client.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def __init__(self, postgres_config: PostgresConfig, rabbitmq_config: RabbitmqCon
2323

2424
def connect(self):
2525
PostgresClient._connect_postgres(self)
26-
RabbitmqClient._connect_rabbitmq(self)
26+
RabbitmqClient._start_rabbitmq(self)
2727

2828
def stop(self):
2929
PostgresClient._close_postgres(self)

src/nwnsdk/rabbitmq/rabbitmq_client.py

+21-10
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#!/usr/bin/env python
22

33
import logging
4+
import threading
45
from enum import Enum
56
from typing import Callable, Dict
67
from uuid import uuid4
@@ -32,7 +33,7 @@ def from_workflow_type(workflow_type: WorkFlowType) -> "Queue":
3233
raise RuntimeError(f"Unimplemented workflow type {workflow_type}. Please implement.")
3334

3435

35-
class RabbitmqClient:
36+
class RabbitmqClient(threading.Thread):
3637
rabbitmq_is_running: bool
3738
rabbitmq_config: RabbitmqConfig
3839
rabbitmq_exchange: str
@@ -41,6 +42,7 @@ class RabbitmqClient:
4142
queue: str
4243

4344
def __init__(self, config: RabbitmqConfig):
45+
super().__init__()
4446
self.rabbitmq_is_running = False
4547
self.rabbitmq_config = config
4648
self.rabbitmq_exchange = config.exchange_name
@@ -59,7 +61,7 @@ def _connect_rabbitmq(self):
5961
self.rabbitmq_config.port,
6062
"/",
6163
credentials,
62-
heartbeat=3600,
64+
heartbeat=60,
6365
blocked_connection_timeout=3600,
6466
connection_attempts=10,
6567
)
@@ -73,15 +75,24 @@ def _connect_rabbitmq(self):
7375
self.channel.queue_bind(self.queue, self.rabbitmq_exchange, routing_key=Queue.StartWorkflowOptimizer.value)
7476
LOGGER.info("Connected to RabbitMQ")
7577

76-
def wait_for_work(self, callbacks: Dict[Queue, PikaCallback]):
78+
def _start_rabbitmq(self):
79+
self._connect_rabbitmq()
80+
self.start()
81+
82+
def set_callbacks(self, callbacks: Dict[Queue, PikaCallback]):
83+
for queue, callback in callbacks.items():
84+
self.connection.add_callback_threadsafe(lambda: self.channel.basic_consume(queue=queue.value,
85+
on_message_callback=callback,
86+
auto_ack=False))
87+
88+
def run(self):
7789
self.rabbitmq_is_running = True
7890

7991
while self.rabbitmq_is_running:
8092
try:
81-
for queue, callback in callbacks.items():
82-
self.channel.basic_consume(queue=queue.value, on_message_callback=callback, auto_ack=False)
8393
LOGGER.info("Waiting for input...")
84-
self.channel.start_consuming()
94+
while self.rabbitmq_is_running:
95+
self.connection.process_data_events(time_limit=1)
8596
except pika.exceptions.ConnectionClosedByBroker as exc:
8697
LOGGER.info('Connection was closed by broker. Reason: "%s". Shutting down...', exc.reply_text)
8798
except pika.exceptions.AMQPConnectionError:
@@ -96,11 +107,11 @@ def _send_start_work_flow(self, job_id: uuid4, work_flow_type: WorkFlowType):
96107

97108
def _send_output(self, queue: Queue, message: str):
98109
body: bytes = message.encode("utf-8")
99-
self.channel.basic_publish(exchange=self.rabbitmq_exchange, routing_key=queue.value, body=body)
110+
self.connection.add_callback_threadsafe(lambda: self.channel.basic_publish(exchange=self.rabbitmq_exchange,
111+
routing_key=queue.value,
112+
body=body))
100113

101114
def _stop_rabbitmq(self):
102115
self.rabbitmq_is_running = False
103-
if self.channel:
104-
self.channel.stop_consuming()
105116
if self.connection:
106-
self.connection.close()
117+
self.connection.add_callback_threadsafe(lambda: self.connection.close())

0 commit comments

Comments
 (0)