Chapter 6. Message Filtering

There may be times when you want to be more selective about the messages received from a particular queue or topic. Without message filtering, topic subscribers receive every message published to the topic and queue receivers receive the next available message, regardless of the message content or type. In the case of topic subscribers, the subscriber may be forced to process a large number of unnecessary and unwanted messages, usually leading to custom-written Java code to manually filter unwanted messages. A good example of this is with the TBorrower class from the prior chapter. In this case, the TBorrower class is receiving every loan rate published from the TLender on the RateTopic topic, and then using conditional logic to determine whether to refinance the existing mortgage loan:

public class TBorrower implements javax.jms.MessageListener {

    ...
    public TBorrower(String topiccf, String topicName, String rate) {    
        try {
            ...
            TopicSubscriber subscriber = 
                session.createSubscriber();
            ...
    }

    public void onMessage(Message message) {
       try {
          // Get the data from the message
          BytesMessage msg = (BytesMessage)message;
          double newRate = msg.readDouble();
       
          // If the rate is at least 1 point lower than the current rate, then 
          //recommend refinancing
          if ((currentRate - newRate) >= 1.0) {
             System.out.println(
                 "New rate = " + newRate + " - Consider refinancing loan");
          } else {
             System.out.println("New rate = " + newRate + " - Keep existing loan");
          } System.out.println("\nWaiting ...

Get Java Message Service, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.