Created
May 13, 2025 23:37
-
-
Save pintowar/ed77facd450fd74aac120334c421e756 to your computer and use it in GitHub Desktop.
Simple pub/sub sample using rabbitmq. To run python scripts, just run `uv run sub.py`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
version: "3.9" | |
services: | |
rabbitmq: | |
image: rabbitmq:3-management | |
container_name: rabbitmq | |
ports: | |
- 5672:5672 | |
- 15672:15672 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /// script | |
# dependencies = [ | |
# "pika", | |
# ] | |
# /// | |
import pika | |
connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost")) | |
channel = connection.channel() | |
# channel.exchange_declare(exchange='amq.fanout', exchange_type='fanout') | |
print("write a message ('quit' to exit)") | |
message = None | |
while message != "quit": | |
message = input() | |
channel.basic_publish(exchange="amq.fanout", routing_key="my.poc", body=message) | |
print(f" [x] Sent: {message}") | |
connection.close() | |
print("exiting publisher!") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /// script | |
# dependencies = [ | |
# "pika", | |
# ] | |
# /// | |
import pika | |
import random | |
import string | |
connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost")) | |
channel = connection.channel() | |
# channel.exchange_declare(exchange='amq.fanout', exchange_type='fanout') | |
suffix = "".join(random.choices(string.ascii_uppercase + string.digits, k=5)) | |
queue_name = f"my.poc.{suffix}" | |
result = channel.queue_declare(queue=queue_name, exclusive=True) | |
channel.queue_bind(exchange="amq.fanout", queue=queue_name) | |
print(" [*] Waiting for messages. To exit press CTRL+C") | |
def callback(ch, method, properties, body): | |
print(f" [x] {body}") | |
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True) | |
channel.start_consuming() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment