我最近在jms中使用Topic,遇到了问题。我的TopicSubscriber没有收到发布者的消息,我也不明白为什么。
这是我的TopicPublisher:
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
那是什么问题我在做什么错,如何解决?
答案 0 :(得分:1)
在创建订阅之前,您似乎正在发送消息。 JMS主题使用发布-订阅语义,其中任何发布的消息都传递给所有订阅。如果没有订阅,则消息将被丢弃。
此外,由于您使用的是receiveNoWait()
,因此将大大减少客户收到消息的机会。为了使您的客户实际接收到一条消息,必须在您致电createSubscriber(topic)
到您致电receiveNoWait()
的这段时间之间发送该消息。由于这两个通话非常靠近,因此时间窗口很小。
如果您确实希望订阅者收到消息,请先运行Subscriber
,然后使用receive()
而不是receiveNoWait()
,然后运行Publisher
。这样可以确保发送消息时订阅存在,并且客户端在退出之前等待接收消息。