SoFunction
Updated on 2025-04-05

Java connection MQ to implement information query operation process

Java connection MQ to implement information query

In distributed systems, message queues (MQ) are a common technology used to implement decoupling, messaging and asynchronous communication between systems. This article will introduce how to connect to MQ using Java and implement information query.

1. Preparation

First, we need to select a suitable message queue system as an example. In this article, we select Apache RocketMQ as the message queue service. You can choose other MQ systems according to the actual situation. Secondly, make sure you have installed and configured the selected message queue system, obtain the corresponding dependency library and introduce it into the Java project.

2. Write Java code to connect to MQ

javaCopy code
import ;
import ;
import ;
public class MQProducer {
    public static void main(String[] args) {
        try {
            DefaultMQProducer producer = new DefaultMQProducer("example_group");
            ("localhost:9876");
            ();
            Message msg = new Message("TopicTest", "TagA", "Hello MQ".getBytes());
            SendResult sendResult = (msg);
            ("SendResult: %s%n", sendResult);
            ();
        } catch (Exception e) {
            ();
        }
    }
}

The above code creates aDefaultMQProducerObject, and set the Topic, Tag and content of the message to send, and then send the message to the message queue. In actual projects, you can also add exception handling, message confirmation and other logic.

3. Write Java code to implement information query

javaCopy code
import ;
import .*;
import ;
import ;
public class MQConsumer {
    public static void main(String[] args) {
        try {
            DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("example_group");
            ("localhost:9876");
            ("TopicTest", "*");
            (new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                    for (MessageExt msg : msgs) {
                        ("%s Receive New Messages: %s %n", ().getName(), new String(()));
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            ();
            ("Consumer Started.%n");
        } catch (Exception e) {
            ();
        }
    }
}

The above code creates aDefaultMQPushConsumerObject, and set up the Topic of the consumption group and message subscription, then register the message listener, consume and process the message in real time. In actual projects, you can parse and query the message content.

4. Run the code

Compile and run the above code and you will see the process of the producer sending messages to the message queue and the consumer receiving and processing messages. In this way, you can implement MQ-based information query function.

The online mall's order processing system demonstrates how to use Java to connect to MQ to implement information query functions. Suppose we have an order system, and after the order is created, we need to asynchronously notify the inventory system for inventory deduction.

Scene description

  • The order system creates an order and sends order information to MQ;
  • The inventory system monitors order messages in MQ, receives order information and deducts inventory;
  • After the inventory system is processed, the result information is sent to MQ;
  • The order system monitors the inventory result messages in MQ, receives inventory deduction result information, and updates the order status.

Sample code

The order system sends order information to MQ

javaCopy code
import ;
import ;
import ;
public class OrderMQProducer {
    public static void main(String[] args) {
        try {
            DefaultMQProducer producer = new DefaultMQProducer("order_group");
            ("localhost:9876");
            ();
            // Simulate order information            String orderInfo = "Order ID: 123456, Product ID: 789, Quantity: 2";
            Message msg = new Message("OrderTopic", "OrderTag", ());
            SendResult sendResult = (msg);
            ("Order message sent successfully. SendResult: " + sendResult);
            ();
        } catch (Exception e) {
            ();
        }
    }
}

The inventory system monitors MQ and processes order information

import ;
import .*;
import ;
import ;
public class InventoryMQConsumer {
    public static void main(String[] args) {
        try {
            DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("inventory_group");
            ("localhost:9876");
            ("OrderTopic", "OrderTag");
            (new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List&lt;MessageExt&gt; msgs, ConsumeConcurrentlyContext context) {
                    for (MessageExt msg : msgs) {
                        // Simulated inventory deduction logic                        String orderInfo = new String(());
                        ("Received order message: " + orderInfo);
                        ("Inventory deduction processing...");
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            ();
            ("Inventory system started listening for order messages.");
        } catch (Exception e) {
            ();
        }
    }
}

Through the above example code, the order system can send order information to MQ, and the inventory system listens to MQ and processes the order information, realizing the decoupling between the order and the inventory system. This method can improve the reliability and scalability of the system, while improving the overall performance and user experience of the system.

Apache RocketMQ is an open source distributed messaging middleware system that was originally developed by Alibaba Group and contributed to the Apache Software Foundation. RocketMQ provides reliable messaging and distributed messaging publish/subscribe features, with high throughput, low latency, high availability and scalability, suitable for messaging communication in large-scale distributed systems. Here are some of the main features of Apache RocketMQ:

  • Distributed architecture: RocketMQ's architecture is divided into multiple components, including Name Server, Broker, Producer and Consumer. Each component works together to achieve reliable message delivery and processing.
  • High Performance: RocketMQ supports high throughput transmission of hundreds of thousands of messages per second. Message storage uses sequential writing disks to improve performance, while supporting batch sending and receiving messages, improving efficiency.
  • Reliability: RocketMQ provides a variety of messaging methods, including synchronous transmission, asynchronous transmission and one-way transmission, ensuring reliable message delivery. In addition, a message retry mechanism and fault tolerance mechanism are provided to ensure the reliability of message delivery.
  • Rich features: RocketMQ provides rich features, including sequential message delivery, transaction message, delayed message, message filtering, message trajectory, etc., to meet the needs of various complex application scenarios.
  • Horizontal scaling: RocketMQ supports dynamic addition of Broker nodes in the cluster to achieve horizontal scaling and load balancing, and improve system scalability.
  • Monitoring and Management: RocketMQ provides detailed monitoring and management functions, including statistical information on message sending and consumption, message accumulation status, Broker node operation status, etc., to facilitate operation and maintenance personnel to monitor and manage the entire message system.

in conclusion

Through the above steps, we successfully connect to MQ using Java and implement information query function. Message queue technology can well realize decoupling and asynchronous communication between systems, providing important support for building efficient distributed systems. I hope the content of this article can help you understand and apply MQ technology.

This is the end of this article about Java connection MQ to implement information query. For more related Java MQ information query content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!