使用服务总线将消息从发送/发布到RabbitMQ?

fgw7neuy  于 2023-01-05  发布在  RabbitMQ
关注(0)|答案(1)|浏览(195)

我知道可以从RabbitMQ发送消息到Azure服务总线,Microsoft Azure中的文档。
在我的用例中,我希望执行相反的操作:从Azure服务总线发送消息到RabbitMQ并被使用。2可以吗?3谢谢。

koaltpgm

koaltpgm1#

是的,您可以使用Service Bus将消息发送/发布到RabbitMQ,此脚本可以处理您的问题:

# Import the libraries
import pika
import os
from azure.servicebus import ServiceBusClient, ServiceBusMessage

CONNECTION_STR = "Endpoint=sb://......."
QUEUE_NAME = "Queue name"

# Create a Service Bus client using the connection string
servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)

# Connect to RabbitMQ
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672, '/', credentials))
channel = connection.channel()

# Declare a queue and bind it to an exchange
channel.queue_declare(queue=QUEUE_NAME)
channel.queue_bind(exchange='amq.topic', queue=QUEUE_NAME)

# Create a Service Bus receiver
with servicebus_client:
    receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME)
    with receiver:
        # Receive messages from the queue
        received_msgs = receiver.receive_messages(max_wait_time=5)
        for msg in received_msgs:
            # Print the message
            print(str(msg))
            # Send the message to RabbitMQ
            channel.basic_publish(exchange='amq.topic', routing_key=QUEUE_NAME, body=str(msg))
            # Complete the message
            
# Close the connection to RabbitMQ
connection.close()
print('Exiting')

相关问题