What is the Publish-Subscribe pattern and why is it important?
It’s a messaging pattern where senders (publishers) send messages without targeting specific receivers, and receivers (subscribers) listen for messages of interest.
How does the Pub-Sub model differ from the Request-Response model?
In Pub-Sub, publishers and subscribers are decoupled, while in Request-Response, the requester waits for a response from the responder.
How can Java applications implement a Pub-Sub model?
Java apps can use messaging systems like Apache Kafka, RabbitMQ, or Google Cloud Pub/Sub.
// Using Google Cloud Pub/Sub Java client
Publisher publisher = Publisher.newBuilder(topicName).build();
publisher.publish(PubsubMessage.newBuilder().setData(data).build());
What are some challenges of the Pub-Sub model in distributed systems?
Challenges include message ordering, ensuring at-least-once or at-most-once delivery, and handling large volumes of messages.
How can you ensure message durability in a Pub-Sub system?
Use persistent storage for messages and mechanisms like acknowledgments to confirm message processing.
How do you handle slow subscribers in a Pub-Sub system?
Implement back-pressure mechanisms, use buffering, or scale out subscriber instances.
For example, we have a simple publisher that produces messages at a fixed rate and a subscriber that processes messages at a slower rate. The BlockingQueue is used to manage the messages between the publisher and subscriber. The publisher puts messages into the queue, and the subscriber takes messages from the queue. This simple mechanism helps in controlling the flow of messages and provides a form of back-pressure by limiting the rate at which messages are published and processed.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Publisher implements Runnable {
private BlockingQueue<String> messageQueue;
public Publisher(BlockingQueue<String> messageQueue) {
this.messageQueue = messageQueue;
}
@Override
public void run() {
try {
int messageCount = 0;
while (true) {
String message = "Message " + messageCount++;
messageQueue.put(message); // Publish the message
System.out.println("Published: " + message);
Thread.sleep(500); // Simulate message production
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
class Subscriber implements Runnable {
private BlockingQueue<String> messageQueue;
public Subscriber(BlockingQueue<String> messageQueue) {
this.messageQueue = messageQueue;
}
@Override
public void run() {
try {
while (true) {
String message = messageQueue.take(); // Consume the message
System.out.println("Subscriber received: " + message);
// Simulate message processing
Thread.sleep(1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class PubSubWithBackPressure {
public static void main(String[] args) {
int queueCapacity = 10;
BlockingQueue<String> messageQueue = new ArrayBlockingQueue<>(queueCapacity);
ExecutorService executor = Executors.newFixedThreadPool(2);
// Create a publisher and a subscriber
Publisher publisher = new Publisher(messageQueue);
Subscriber subscriber = new Subscriber(messageQueue);
executor.submit(publisher);
executor.submit(subscriber);
// Shutdown the executor after 10 seconds
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
In the context of Java, how can you achieve real-time Pub-Sub?
Use WebSockets for real-time communication or systems like Apache Kafka for near-real-time messaging.
// Using Java WebSocket API
@OnMessage
public void onMessage(Session session, String message) {
// Handle message
}
How do you ensure message ordering in a Pub-Sub system?
Use ordered queues, sequence numbers, or systems that inherently support ordering like Apache Kafka’s partitions.
How can you filter messages in a Pub-Sub system?
Use topic-based filtering, content-based filtering, or systems that support native filtering like Google Cloud Pub/Sub.
How do you handle dead-letter messages in a Pub-Sub system?
Use dead-letter queues to store unprocessable messages for later inspection or reprocessing.
In the vast symphony of backend engineering, the Pub-Sub model stands out as a harmonious solution to asynchronous communication challenges. As Java engineers, understanding the nuances of this pattern is akin to mastering the notes of a complex musical piece. Whether it’s the rhythmic dance of publishers and subscribers or the crescendo of real-time messaging, the Pub-Sub model offers a melody of scalability, decoupling, and efficiency. As we continue our journey in the world of distributed systems, may our applications communicate seamlessly, and our understanding deepens. Until our next exploration, keep coding to the rhythm of innovation!
Note :
The Publish-Subscribe pattern/model is same as Application Event in Lighting Component. If you want to communicate between components those are not bounding in parent child relationship, but available in same page (say, in same app-builder page), then we will use publish-subscribe pattern.
In a publish-subscribe pattern, one component publishes an event. Other components subscribe to receive and handle the event. Every component that subscribes to the event receives the event. The pubsub module restricts events to a single page. You must also manually unregister all components that are registered to pubsub.
Note : The pubsub module is not officially supported or actively maintained.
To communicate between components that aren’t in the same DOM tree, use a singleton library that follows the publish-subscribe pattern.
Pubsub Component : The Pubsub Component enables data sharing and passing messages between components that aren’t ancestors. Multiple components can register and receive data from the same channel.
This component exposes 4 functions:
register
unregister
fire
shouldExecuteCallbackHandler.shouldExecuteCallback
To use your component as a listener, add your handler object with the events it wants to handle as a property on your LWC. Then, unregister the handlers in the disconnectedCallback. It’s important to unregister components to ensure that you don’t leak DOM components into memory or cause potential errors by continuing to receive and process events on disconnected and disposed LWC components.
Building greater futures through innovation and collective knowledge
Tech SkillBirds Enterprise is an IT services, consulting and business solutions organization that has been partnering with many of the world’s largest businesses for the past 13 years. We believe innovation and collective knowledge can transform all our futures with greater purpose.
Website : www.techskillbirds.com
Telegram : https://t.me/techskillbirds
What's Up : +91 63010 61963
Facebook : profile.php?id=61565870777368
Instagram : techskillbirds/
LinkedIn : company/skillbirds-acquire-enterprise/
YouTube : /@techskillbirds638/videos
Pinterest : TechSkillBirds/
Twitter : @techskillbirds
urbanpro : hyderabad/tech-skillbirds-enterprise-hitec-city/32237376
JustDail : Hyderabad/Tech-Skillbirds-Enterprise-Secunderabad-City
Indiamart: skillbirds-acquire-enterprise/
About Us : https://www.techskillbirds.com/
Services : https://www.techskillbirds.com/blank-1
Buy Services : https://www.techskillbirds.com/book-o...
Corporate Trainings : https://www.techskillbirds.com/shop
Software Training : https://www.techskillbirds.com/s-proj...
Blog : https://www.techskillbirds.com/blog
Contact Us : https://www.techskillbirds.com/about-1
Plans & Pricing : https://www.techskillbirds.com/plans-...
Comments