The before code shows a direct call from ServiceA to ServiceB, causing tight coupling and blocking. The after code uses RabbitMQ to send messages asynchronously; ServiceA publishes messages to a queue, and ServiceB consumes them independently, improving decoupling and reliability.
### Before: Direct synchronous call (no message broker)
class ServiceA:
def send_data(self, data):
service_b = ServiceB()
service_b.process_data(data)
class ServiceB:
def process_data(self, data):
print(f"Processing {data}")
### After: Using RabbitMQ message broker
import pika
class ServiceA:
def send_data(self, data):
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
channel.basic_publish(
exchange='',
routing_key='task_queue',
body=data.encode(),
properties=pika.BasicProperties(delivery_mode=2))
connection.close()
class ServiceB:
def start_consuming(self):
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
def callback(ch, method, properties, body):
print(f"Processing {body.decode()}")
ch.basic_ack(delivery_tag=method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='task_queue', on_message_callback=callback)
channel.start_consuming()