Advertisement
vitareinforce

stress test rmq

May 14th, 2025
507
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. import pika
  2. import sys
  3. import time
  4. import keyboard  # Import the keyboard library
  5.  
  6. def connect_and_publish(client_id, user, password, host, queue_name):
  7.     """Connect to RabbitMQ and publish messages with client ID set in connection properties."""
  8.     credentials = pika.PlainCredentials(user, password)
  9.     parameters = pika.ConnectionParameters(
  10.         host=host,
  11.         credentials=credentials,
  12.         client_properties={
  13.             'connection_name': client_id
  14.         }
  15.     )
  16.  
  17.     connection = None
  18.     for i in range(5):
  19.         try:
  20.             connection = pika.BlockingConnection(parameters)
  21.             print(f"Connected to RabbitMQ with client ID '{client_id}'")
  22.             break
  23.         except pika.exceptions.AMQPConnectionError:
  24.             print(f"Connection failed, retrying in 5 seconds... ({i+1}/5)")
  25.             time.sleep(5)
  26.     else:
  27.         print("Failed to connect to RabbitMQ after 5 attempts.")
  28.         sys.exit(1)
  29.  
  30.     channel = connection.channel()
  31.  
  32.     # Declare queue to publish to
  33.     channel.queue_declare(queue=queue_name, durable=False)
  34.  
  35.     print("Press 'Esc' to stop publishing messages.")
  36.  
  37.     # Loop to publish messages until 'Esc' is pressed
  38.     while True:
  39.         if keyboard.is_pressed('esc'):  # Check if 'Esc' key is pressed
  40.             print("Escape key pressed. Stopping the publisher.")
  41.             break
  42.  
  43.         # Create a message
  44.         message = f"Hello RabbitMQ! This is a test message from client_id {client_id}."
  45.        
  46.         # Publish message
  47.         channel.basic_publish(
  48.             exchange='amq.topic',
  49.             routing_key=queue_name,
  50.             body=message,
  51.             properties=pika.BasicProperties(
  52.                 delivery_mode=2,  # Persistent message
  53.             )
  54.         )
  55.  
  56.         print(f"Published message to queue '{queue_name}': {message}")
  57.         time.sleep(1)  # Sleep for a second before publishing the next message
  58.  
  59.     # Close connection
  60.     connection.close()
  61.     print("Connection closed.")
  62.  
  63. if __name__ == "__main__":
  64.     # Configuration
  65.     CLIENT_ID = "punclut516"
  66.     USERNAME = "camera"
  67.     PASSWORD = "camera"
  68.     HOST = "localhost"
  69.     QUEUE_NAME = "camera"
  70.  
  71.     connect_and_publish(CLIENT_ID, USERNAME, PASSWORD, HOST, QUEUE_NAME)
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement