ActiveMQ synchronously waits to receive messages

Need to simulate an MQ consumer receiving messages synchronously:

The scene is as follows: there are 2 APPs, called APP1, APP2 and APP3

  1. APP1 sends a request to APP2, APP2 then requests APP3, the calculation is done by APP3, we cannot change APP2, but we can change APP3
  2. APP1 has to wait for the result of APP2 to return synchronously, which can be polled by HTTP, but it consumes too much resources, so think of MQ
  3. APP3 finishes calculating and sends an MQ message
  4. APP1 received MQ message
  5. Continue to the next operation

To achieve how APP1 synchronizes waiting for APP3 messages.

surroundings

ActiveMQ: 5.15.9
JDK: 1.8

achieve

    @Test
    public void testMQ() throws Exception {
        log.info("开始...");
        final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
                "user", "password", "tcp://host:61616");
        final Connection connection = factory.createConnection();
        connection.start();
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        log.info("Session 创建完");
        receiveFromQueue(session, "jimo-q1");

        // 第二个queue
        receiveFromQueue(session, "jimo-q2");

        log.info("结束");
        connection.close();
    }

    private void receiveFromQueue(Session session, String queueName) throws JMSException {
        final Queue queue = session.createQueue(queueName);
        final MessageConsumer consumer = session.createConsumer(queue);
        /*consumer.setMessageListener((m) -> {
            try {
                System.out.println(((TextMessage) m).getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        });*/
        // 同步等待一条消息,最多等待10分钟
        final Message msg = consumer.receive(10 * 60 * 1000L);
        System.out.println(queueName + ":" + ((TextMessage) msg).getText());
    }

verification

Run the production message command on the activemq command line:

./activemq producer --user user --password password --destination queue://jimo-q1 --brokerUrl tcp://host:61616 --messageCount 1
./activemq producer --user user --password password --destination queue://jimo-q2 --brokerUrl tcp://host:61616 --messageCount 1

You can see the log output

2020 三月 03 09:06:42,731 [main] [INFO] [ServiceTest]: ServiceTest.testMQ( ServiceTest.java:48) - 开始...
2020 三月 03 09:06:43,157 [main] [INFO] [ServiceTest]: ServiceTest.testMQ( ServiceTest.java:54) - Session 创建完
jimo-q1:test message: 0
jimo-q2:test message: 0
2020 三月 03 09:06:55,865 [main] [INFO] [ServiceTest]: ServiceTest.testMQ( ServiceTest.java:60) - 结束
Published 80 original articles · Like 319 · Visits 340,000+

Guess you like

Origin blog.csdn.net/jimo_lonely/article/details/104929573