nonchalant
nonchalant

Reputation: 13

Producer consumer pattern in JAVA

Here the pattern of consumer-producer

Producer creates a new message, consumer listens for them via Broker.

So far, producer creates and sends a message while consumer waits for message. When new message comes consumer prints it to the screen.

I want Producer to be informed that Consumer has received the message and dequeued it.

I wonder is there any way to notify/feedack Producer from Consumer? Or should I inform Consumer via Broker? How can do it?

Upvotes: 1

Views: 770

Answers (3)

vitrums
vitrums

Reputation: 512

It's more like Listener pattern. Use EventBus. 2 events: public PutEvent(MyType message) {...}, public TakeEvent(long id) {...}. Then:

EventBus bus = new SimpleEventBus();
bus.addHandler(producerInstance::onMessageTaken, GetEvent.getType());
bus.addHandler(consumerInstance::onMessageArrived, PutEvent.getType());

Consumer:

MyType message = queue.pop();
bus.fireEventFromSource(new TakeEvent(message.getId()), this);
...
@Override public void onMessageArrived(PutEvent event) {
  // We know, that there're messages out there and can later pop it
  System.out.printf("%d from %s", event.getMessage().getId(), event.getSource() != null ? event.getSource().hashCode() + "" : "unknown");
}

Producer:

MyType message = new MyType(data, ++id);
queue.add(message);
bus.fireEventFromSource(new PutEvent(message), this);
...
@Override public void onMessageTaken(TakeEvent event) {
  // Wow, who took it?
  System.out.printf("%s took %d", event.getSource() != null ? event.getSource().hashCode() + "" : "unknown", event.getId());
}

Upvotes: 0

jason.kaisersmith
jason.kaisersmith

Reputation: 9620

The JMS standard supports a Reply Queue (JMSReplyTo), so that the original consumer can return a reply message to the original producer on the specific queue.

As shown here;

http://www.enterpriseintegrationpatterns.com/patterns/messaging/RequestReplyJmsExample.html

enter image description here

If you also use the JMSCorrelationID, then you can link the messages together, so that you know the reply relates to the specific request with id xxxxx.

Of coruse this then means the the consumer will become a producer for the reply message.

The link provided also has code to show a working example (although I have not tried it myself)

Upvotes: 2

duffymo
duffymo

Reputation: 308848

I'd ask why the Producer needs to know.

The whole purpose of producer/consumer is to decouple the two objects. Producers don't know or care who handles the message.

Your proposal breaks that model. You should not do so unless you have a very good reason besides "I want to."

If you must, give the consumer class a reference to the producer and expose a method on it that can be used to send the message. Or couple them in a database by having the consumer write to a table that the producer can also query.

But now the two are hopelessly entangled. I think it's a bad choice.

Upvotes: 1

Related Questions