From 01b02a09bf7c07da54269c00a1f926bfbb93201f Mon Sep 17 00:00:00 2001
From: "Bo-Chun Louis Chen(VM)" <louistw@uab.edu>
Date: Tue, 17 Mar 2020 01:48:08 +0000
Subject: [PATCH] Update RCRMQ class

publish funtion:
 only make connection if it is not yet established
 only disconnect if there's no consumer using the same connection

consume function:
 only make connection if it is not yet established
 adding _consuming variable to keep tracking if the connection needs to be alive
---
 rc_rmq.py | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/rc_rmq.py b/rc_rmq.py
index 35922b2..41ec7b3 100644
--- a/rc_rmq.py
+++ b/rc_rmq.py
@@ -82,13 +82,15 @@ class RCRMQ(object):
         if 'routing_key' in obj:
             self.ROUTING_KEY = obj['routing_key']
 
-        self.connect()
+        if self._connection is None:
+            self.connect()
 
         self._channel.basic_publish(exchange=self.EXCHANGE,
                 routing_key=self.ROUTING_KEY,
                 body=json.dumps(obj['msg']))
 
-        self.disconnect()
+        if not self._consuming:
+            self.disconnect()
 
     def start_consume(self, obj):
         if 'queue' in obj:
@@ -100,9 +102,11 @@ class RCRMQ(object):
         if self.DEBUG:
             print("Queue: " + self.QUEUE + "\nRouting_key: " + self.ROUTING_KEY)
 
-        self.connect()
+        if self._connection is None:
+            self.connect()
 
         self._consumer_tag = self._channel.basic_consume(self.QUEUE,obj['cb'])
+        self._consuming = True
         try:
             self._channel.start_consuming()
         except KeyboardInterrupt:
-- 
GitLab