Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pika
- import sys
- import time
- import keyboard # Import the keyboard library
- def connect_and_publish(client_id, user, password, host, queue_name):
- """Connect to RabbitMQ and publish messages with client ID set in connection properties."""
- credentials = pika.PlainCredentials(user, password)
- parameters = pika.ConnectionParameters(
- host=host,
- credentials=credentials,
- client_properties={
- 'connection_name': client_id
- }
- )
- connection = None
- for i in range(5):
- try:
- connection = pika.BlockingConnection(parameters)
- print(f"Connected to RabbitMQ with client ID '{client_id}'")
- break
- except pika.exceptions.AMQPConnectionError:
- print(f"Connection failed, retrying in 5 seconds... ({i+1}/5)")
- time.sleep(5)
- else:
- print("Failed to connect to RabbitMQ after 5 attempts.")
- sys.exit(1)
- channel = connection.channel()
- # Declare queue to publish to
- channel.queue_declare(queue=queue_name, durable=False)
- print("Press 'Esc' to stop publishing messages.")
- # Loop to publish messages until 'Esc' is pressed
- while True:
- if keyboard.is_pressed('esc'): # Check if 'Esc' key is pressed
- print("Escape key pressed. Stopping the publisher.")
- break
- # Create a message
- message = f"Hello RabbitMQ! This is a test message from client_id {client_id}."
- # Publish message
- channel.basic_publish(
- exchange='amq.topic',
- routing_key=queue_name,
- body=message,
- properties=pika.BasicProperties(
- delivery_mode=2, # Persistent message
- )
- )
- print(f"Published message to queue '{queue_name}': {message}")
- time.sleep(1) # Sleep for a second before publishing the next message
- # Close connection
- connection.close()
- print("Connection closed.")
- if __name__ == "__main__":
- # Configuration
- CLIENT_ID = "punclut516"
- USERNAME = "camera"
- PASSWORD = "camera"
- HOST = "localhost"
- QUEUE_NAME = "camera"
- connect_and_publish(CLIENT_ID, USERNAME, PASSWORD, HOST, QUEUE_NAME)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement