📄 topicconsumer.java
字号:
package com.wls8unleashed.jms;
import javax.jms.*;
import javax.naming.*;
/**
* Implements a basic subscriber to a JMS topic.
* Extends the TopicManager for some basic initialization
* help.
*/
public class TopicConsumer extends TopicManager
implements MessageListener {
private TopicSubscriber topicSubscriber;
public boolean quitFromReceiving = false;
/**
* Constructor creates all of the objects to receive messages
*/
public TopicConsumer(Context context)
throws NamingException, JMSException {
// Call superclass constructor
super(context);
// Create subscriber
System.out.println("Creating topic subscriber...");
topicSubscriber = topicSession.createSubscriber(topic);
// Register subscriber as a MessageListener
System.out.println("Setting message listener...");
topicSubscriber.setMessageListener(this);
// Start the connection thread
System.out.println("Starting connection thread...");
topicConnection.start();
}
/**
* Implements the message listener and prints a message.
*/
public void onMessage(Message message) {
MessageHandler handler = new MessageHandler();
handler.onMessage(message);
}
/**
* Close JMS related objects.
*/
public void close() throws JMSException {
topicSubscriber.close();
this.topicSession.close();
this.topicConnection.close();
}
/**
* Main method used to execute the TopicConsumer example
*/
public static void main(String[] args){
try {
// Create JNDI context
Context context = Props.getInitialContext();
// Create new TopicConsumer
System.out.println("Creating new TopicConsumer...");
TopicConsumer topicConsumer = new TopicConsumer(context);
System.out.println(" TopicConsumer is ready to receive messages.");
// Receive messages until user quits from program or quit flags true.
synchronized (topicConsumer) {
while (!topicConsumer.quitFromReceiving) {
try {
// Wait for messages
topicConsumer.wait();
} catch (InterruptedException interruptedException) {
System.out.println("Interruption!");
interruptedException.printStackTrace();
}
}
}
// Close up resources when done and exit
topicConsumer.close();
context.close();
System.exit(0);
}catch(Exception e){
System.out.println("Problem executing topic consumer");
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -