主题订阅者未收到消息

问题描述 投票:1回答:1

我最近在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();
    }
}

我的TopicSubscriber:

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();
    }
}

在我的订阅者中,我在qazxsw poi上有一个空指针是什么问题?我做错了什么以及如何解决?

java jms activemq jms-topic
1个回答
1
投票

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

此外,由于您正在使用message.getText(),因此严重降低了客户端获取消息的机会。为了让您的客户实际收到消息,您必须在调用receiveNoWait()和调用createSubscriber(topic)之间发送消息。由于这两个呼叫非常接近,因此时间窗口非常小。

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

© www.soinside.com 2019 - 2024. All rights reserved.