【发布时间】:2019-09-09 17:23:48
【问题描述】:
我最近在 jms 中使用 Topic,但遇到了问题。我的 TopicSubscriber 没有收到发布者的消息,我不明白为什么。
这是我的主题发布者:
public class Publisher
{
private static final String CONNECTION_URL = "tcp://localhost:61616";
public static void main(String[] args) throws Exception
{
BrokerService service = BrokerFactory.createBroker(new URI("broker:(" + CONNECTION_URL + ")"));
service.start();
TopicConnectionFactory connectionFactory = new ActiveMQConnectionFactory(CONNECTION_URL);
// create a topic connection
TopicConnection topicConn = connectionFactory.createTopicConnection();
// create a topic session
TopicSession topicSession = topicConn.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE);
// lookup the topic object
Topic topic = topicSession.createTopic("test");
// create a topic publisher
TopicPublisher topicPublisher = topicSession.createPublisher(topic);
topicPublisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// create the "Hello World" message
TextMessage message = topicSession.createTextMessage();
message.setText("Hello World");
// publish the messages
topicPublisher.publish(message);
// print what we did
System.out.println("Message published: " + message.getText());
// close the topic connection
topicConn.close();
}
}
我的主题订阅者:
public class Subscriber
{
private static final String CONNECTION_URL = "tcp://localhost:61616";
public static void main(String[] args) throws Exception
{
TopicConnectionFactory connectionFactory = new ActiveMQConnectionFactory(CONNECTION_URL);
// create a topic connection
TopicConnection topicConn = connectionFactory.createTopicConnection();
// create a topic session
TopicSession topicSession = topicConn.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE);
Topic topic = topicSession.createTopic("test");
// create a topic subscriber
TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);
// start the connection
topicConn.start();
// receive the message
TextMessage message = (TextMessage) topicSubscriber.receiveNoWait();
// print the message
System.out.println("Message received: " + message.getText());
// close the topic connection
topicConn.close();
}
}
在我的订阅者中,我在 message.getText() 上有一个 NullPointer
那是什么问题?我做错了什么以及如何解决?
【问题讨论】:
-
你确定
NullPointerException在topicSubscriber.receiveNoWait()上吗?这表明topicSubscriber是null。NullPointerException似乎更有可能来自message.getText(),因为message是null。请确认。 -
是的,我的意思是 message.getText() 为空。但这是因为订阅者没有收到消息。我不明白为什么
标签: java jms activemq jms-topic