A simple implementation of a Publisher-Subscriber (Pub/Sub) messaging pattern in Python. This system allows for decoupled communication between publishers and subscribers through topics.
-
models/subscriber.py: Defines the Subscriber class that represents message consumers__init__(self, id): Initializes subscriber with unique IDget_id(): Returns subscriber's unique identifier
-
models/topic.py: Implements Topic class to manage message queues and subscriptions__init__(self, name): Creates topic with given nameadd_message(message): Adds message to topic's queueget_messages(): Returns all messages in topicget_last_message(): Returns most recent messageadd_subscriber(subscriber): Adds subscriber to topicremove_subscriber(subscriber): Removes subscriber from topic
-
models/publisher.py: Contains Singleton Publisher class for message producers__new__(cls): Ensures single publisher instance__init__(): Initializes publisherpublish(message, topic): Publishes message to specific topicpublish_to_all(message): Publishes message to all available topics
-
services/publishService.py: Handles message publishing operationspublish_to_topic(message, topic_name): Publishes message to specific topicpublish_to_all(message): Uses Singleton publisher to broadcast message to all topics
-
services/subscribeService.py: Manages subscription operations and message retrievalsubscribe(subscriber, topic_name): Subscribes user to topicunsubscribe(subscriber, topic_name): Removes subscriptionread_all_message(subscriber, topic_name): Retrieves all messages from topicread_last_message(subscriber, topic_name): Gets most recent message from topic
repository/topicsRepository.py: Manages topic storage and operationscreate_topic(topic_name): Creates new topicget_topic(topic_name): Retrieves specific topicget_all_topics(): Returns all available topicsdelete_topic(topic_name): Removes topic
pubsub.py: Entry point demonstrating the system's functionality- Creates test topics and subscribers
- Demonstrates subscription management
- Shows message publishing and retrieval
The system implements a Singleton pattern for the Publisher class, ensuring:
- Only one publisher instance exists throughout the application
- Centralized message distribution
- Consistent message broadcasting to all topics
- Thread-safe publishing operations
-
Topic Management
- Topics are created through TopicRepository
- Each topic maintains its own message queue
- Multiple subscribers can subscribe to the same topic
-
Publishing
- Single publisher instance handles all publishing operations
- Publishers can send messages to specific topics
- Global broadcast capability to all topics
- Messages are stored in topic-specific queues
-
Subscribing
- Subscribers can subscribe to multiple topics
- The SubscribeService manages subscriptions
- Subscribers can:
- Read all messages from a topic
- Read only the last message from a topic