Create topics at runtime
There are four ways to create Topic objects at runtime:
- Construct a topic using the one-argument MQTopic constructor
- Construct a topic using the default MQTopic constructor, and then call the setBaseTopicName(..) method
- Use the session's createTopic(..) method
- Use the session's createTemporaryTopic() method
- Example 1: Using MQTopic(..)
- This technique requires a reference to the WebSphere MQ implementation of the JMS Topic interface, and therefore renders the code non-portable.
The constructor takes one argument, which must be a uniform resource identifier (URI). For WebSphere MQ classes for Java Message Service Topics, this must be of the form:
topic://TopicName[?property=value[&property=value]*]For further details on URIs and the permitted name-value pairs, see Sending a message.
The following code creates a topic for nonpersistent, priority 5 messages:
// Create a Topic using the one-argument MQTopic constructor String tSpec = "Sport/Football/Spurs/Results?persistence=1&priority=5"; Topic rtTopic = new MQTopic( "topic://" + tSpec );- Example 2: Using MQTopic(), then setBaseTopicName(..)
- This technique uses the default MQTopic constructor, and therefore renders the code non-portable.
After the object is created, set the baseTopicName property using the setBaseTopicName(..) method, passing in the required topic name.
The topic name used here is the non-URI form, and cannot include name-value pairs. Set these by using the set methods, as described in Set properties with the set method.
The following code uses this technique to create a topic:
// Create a Topic using the default MQTopic constructor Topic rtTopic = new MQTopic(); // Set the object properties using the setter methods ((MQTopic)rtTopic).setBaseTopicName( "Sport/Football/Spurs/Results" ); ((MQTopic)rtTopic).setPersistence(1); ((MQTopic)rtTopic).setPriority(5);- Example 3: Using session.createTopic(..)
- We can also create a Topic object using the createTopic method of TopicSession, which takes a topic URI as follows:
// Create a Topic using the session factory method Topic rtTopic = session.createTopic( "topic://Sport/Football/Spurs/Results" );Although the createTopic method is in the JMS specification, the format of the string argument is vendor-specific. Therefore, using this technique might make your code non-portable.
- Example 4: Using session.createTemporaryTopic()
- A TemporaryTopic is a Topic that can be consumed only by subscribers that are created by the same TopicConnection. A TemporaryTopic is created as follows:
// Create a TemporaryTopic using the session factory method Topic rtTopic = session.createTemporaryTopic();
uj24760_