Search This Blog

2023/04/19

Publisher & Subscriber Pattern

 The publisher-subscriber pattern with a broker, also known

as the pub-sub pattern, is a messaging pattern used in
distributed systems, where publishers publish messages to a topic,
and subscribers receive messages from the topic through a broker.


class Broker {
constructor() {
this.topics = new Map();
this.subscribers = new Map();
}

subscribe(topic, subscriber) {
if (!this.subscribers.has(subscriber)) {
this.subscribers.set(subscriber, new Set());
}
this.subscribers.get(subscriber).add(topic);
if (!this.topics.has(topic)) {
this.topics.set(topic, new Set());
}
this.topics.get(topic).add(subscriber);
}

debugMap() {
console.log('---------------Topics-------------')
for (var [key, value] of this.topics) {
var arr = new Array(...value)
console.log(key + ' = ' + JSON.stringify(arr));
}

console.log('---------------Subcriber-------------')
for (var [key, value] of this.subscribers) {
var arr = new Array(...value)
console.log(JSON.stringify(key) + ' = ' + JSON.stringify(arr));
}
}

unsubscribe(topic, subscriber) {
if (this.subscribers.has(subscriber)) {
this.subscribers.get(subscriber).delete(topic)
}
if (this.topics.has(topic)) {
this.topics.get(topic).delete(subscriber)
}
}

publish(topic, data) {
//this.debugMap()
if (this.topics.has(topic)) {
this.topics.get(topic).forEach(subscriber => {
subscriber.receive(topic, data)
});
} else {
console.log("Broker -->Topic is not available", topic, data)
}
}
}

class Subscriber {
constructor(name,broker) {
this.name = name;
this.broker = broker;
}

receive(topic, data) {
console.log(`${this.name} received event on topic "${topic}": ${data}`);
}

subscribe(topic) {
this.broker.subscribe(topic, this);
}

unsubscribe(topic) {
this.broker.unsubscribe(topic, this);
}
}

class Publisher {
constructor(broker) {
this.broker = broker;
}

publish(topic, data) {
this.broker.publish(topic, data);
}
}

// Example usage:
const broker = new Broker();

const subscriber1 = new Subscriber("Alice",broker);
const subscriber2 = new Subscriber("Bob",broker);
const subscriber3 = new Subscriber("Charlie",broker);

subscriber1.subscribe("topic1");
subscriber2.subscribe("topic1");
subscriber3.subscribe("topic2");

//broker.debugMap()

const publisher = new Publisher(broker);
publisher.publish("topic1", "Event 1");
// Alice received event on topic "topic1": Event 1, Bob
received event on topic "topic1": Event 1

console.log("Alice Unsubscribed to topic1")

subscriber1.unsubscribe("topic1", broker);
publisher.publish("topic1", "Event 2");
// Bob received event on topic "topic1": Event 2
publisher.publish("topic2", "Event 3");
// Charlie received event on topic "topic2": Event 3

No comments:

Post a Comment