Update worker.py
Browse files
worker.py
CHANGED
|
@@ -17,33 +17,53 @@ class RabbitMQWorker:
|
|
| 17 |
self.rabbit_url = os.getenv("RABBITMQ_URL")
|
| 18 |
self.processor = Processor()
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
| 23 |
connection_params = pika.URLParameters(self.rabbit_url)
|
| 24 |
-
connection_params.heartbeat =
|
| 25 |
-
connection_params.blocked_connection_timeout =
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
)
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
def callback(self, ch, method, properties, body):
|
| 49 |
"""Handle incoming RabbitMQ messages"""
|
|
|
|
| 17 |
self.rabbit_url = os.getenv("RABBITMQ_URL")
|
| 18 |
self.processor = Processor()
|
| 19 |
|
| 20 |
+
self.publisher_connection = None
|
| 21 |
+
self.publisher_channel = None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def setup_publisher(self):
|
| 25 |
+
if not self.publiserh_connection or self.publisher_connection.is_closed:
|
| 26 |
connection_params = pika.URLParameters(self.rabbit_url)
|
| 27 |
+
connection_params.heartbeat = 30 # Match the consumer heartbeat
|
| 28 |
+
connection_params.blocked_connection_timeout = 300 # Increase timeout
|
| 29 |
|
| 30 |
+
self.publisher_connection = pika.BlockingConnection(connection_params)
|
| 31 |
+
self.publisher_channel = self.publisher_connection.channel()
|
| 32 |
+
self.publisher_channel.queue_declare(queue="ml_server", durable=True)
|
| 33 |
+
|
| 34 |
+
def publish_message(self, body_dict: dict, headers: dict):
|
| 35 |
+
"""Use persistent connection for publishing"""
|
| 36 |
+
max_retries = 3
|
| 37 |
+
for attempt in range(max_retries):
|
| 38 |
+
try:
|
| 39 |
+
# Ensure publisher connection is setup
|
| 40 |
+
self.setup_publisher()
|
| 41 |
+
|
| 42 |
+
self.publisher_channel.basic_publish(
|
| 43 |
+
exchange="",
|
| 44 |
+
routing_key="ml_server",
|
| 45 |
+
body=json.dumps(body_dict),
|
| 46 |
+
properties=pika.BasicProperties(
|
| 47 |
+
delivery_mode=2,
|
| 48 |
+
headers=headers
|
| 49 |
+
)
|
| 50 |
)
|
| 51 |
+
return True
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"Publish attempt {attempt + 1} failed: {e}")
|
| 54 |
+
# Close failed connection
|
| 55 |
+
if self.publisher_connection and not self.publisher_connection.is_closed:
|
| 56 |
+
try:
|
| 57 |
+
self.publisher_connection.close()
|
| 58 |
+
except:
|
| 59 |
+
pass
|
| 60 |
+
self.publisher_connection = None
|
| 61 |
+
self.publisher_channel = None
|
| 62 |
+
|
| 63 |
+
if attempt == max_retries - 1:
|
| 64 |
+
print(f"Failed to publish after {max_retries} attempts")
|
| 65 |
+
return False
|
| 66 |
+
time.sleep(2)
|
| 67 |
|
| 68 |
def callback(self, ch, method, properties, body):
|
| 69 |
"""Handle incoming RabbitMQ messages"""
|