我尝试使用activemq添加消息监听器。我遇到的所有示例都使用嵌套onMessages。我发现Java eclipse不允许这样做(也在stackoverflow上)。所以现在我很困惑如何设置它。当我删除onMessage表单的监听器时,Eclipse告诉我必须在那里实现它。另外,它还希望我在类中实现onMessage方法。所以我在侦听器对象和类中有onMessage。我该如何妥善处理?我没有看到我的代码中有一个onMessage的解决方案。
编辑:代码正在运行且没有错误并收到消息。有两个onMessages
仍然很奇怪public static class HelloWorldConsumer implements Runnable, MessageListener {
@Override
public void run() {
// TODO Auto-generated method stub
// Create a Connection
try {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("Physical");
MessageConsumer consumer = session.createConsumer(topic);
MessageListener listner = new MessageListener() {
@Override
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
System.out.println("Received message : "
+ textMessage.getText() + "'");
}
} catch (JMSException e) {
System.out.println("Caught:" + e);
}
}
};
consumer.setMessageListener(listner);
try {
System.in.read();
} catch (IOException e) {
}
connection.close();
} catch (JMSException ex) {
// Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
}
}//end method
@Override
public void onMessage(Message arg0) {
// TODO Auto-generated method stub
}
}}
答案 0 :(得分:1)
由于您在内联创建MessageListener作为匿名类,因此HelloWorldConsumer类不需要实现MessageListener。