【Java开源代码栏目提醒】:本文主要为网学会员提供TopicReceive.java,希望对需要TopicReceive.java网友有所帮助,学习一下!
package jms;
import javax.jms.*;
import javax.naming.*;
import java.util.*;
public class TopicReceive {
public static void main(String[] args) throws Exception {
Context ctx = getInitialContext();
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx
.lookup("TopicConnectionFactory");
Topic topic = (Topic) ctx.lookup("topic/testTopic");
// Create and get topicConnection from connection factory.
TopicConnection topicConnection = topicConnectionFactory
.createTopicConnection();
// Create and get topicSession from topicConnectiony.
// false means session is not transacted.
TopicSession topicSession = topicConnection.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE);
// Create and get topicSubscriber/text message from topicSession.
TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);
// TopicSubscriber topicSubscriber =
// topicSession.createDurableSubscriber(topic,"durable");
// start delivery of incoming messages
topicConnection.start();
// Receive text messages from topic until
// a non-text message is received indicating end of
// messages.
while (true) {
Message m = topicSubscriber.receive();
if (m instanceof TextMessage) {
TextMessage message = (TextMessage) m;
System.out.println("Reading message: " + message.getText());
} else {
break;
}
}
if (topicConnection != null) {
topicSubscriber.close();
topicSession.close();
topicConnection.close();
}
}
private static Context getInitialContext() throws NamingException {
Hashtable environment = new Hashtable();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory");
environment.put(Context.URL_PKG_PREFIXES,
"org.jboss.naming:org.jnp.interfaces");
environment.put(Context.PROVIDER_URL, "jnp://localhost:1099");
return new InitialContext(environment);
}
}