O'Reilly logo

Java Message Service, 2nd Edition by Richard Monson-Haefel, Mark Richards, David A Chappell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required