gpt4 book ai didi

java - 主题订阅者没有收到消息

转载 作者:行者123 更新时间:2023-11-30 05:40:26 24 4
gpt4 key购买 nike

我最近在 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那是什么问题?我做错了什么以及如何解决?

最佳答案

您似乎是在创建订阅之前发送消息。 JMS 主题使用发布-订阅语义,其中发布的任何消息都会发送到所有订阅。如果没有订阅,则消息将被丢弃。

此外,由于您使用了 receiveNoWait(),您将大大降低客户端收到消息的机会。为了让您的客户端真正收到消息,必须在调用 createSubscriber(topic) 和调用 receiveNoWait() 之间发送消息。由于这两个调用发生的时间非常接近,所以时间窗口非常小。

如果您确实希望订阅者收到消息,请先运行 Subscriber 并使用 receive() 而不是 receiveNoWait(),然后运行Publisher。这将确保发送消息时订阅存在,并且客户端在退出之前等待接收消息。

关于java - 主题订阅者没有收到消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55761847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com