Operation Scenarios
In calling 4.0 Java SDK for example, this article introduces the process of using an open-source SDK to send and receive messages, thus enhancing your comprehension of the complete procedure in messaging.
Note:
Take the Java client as an exemple. For clients employing other languages, please refer to the SDK Documentation. Prerequisites
Resources Creation and Preparation already completed
Steps
Step 1: Install the Java dependency
Incorporate the relevant dependencies in the Java project. Take a Maven project as an example, add the following dependency to pom.xml:
<!-- in your <dependencies> block -->
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>4.9.7</version>
</dependency>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-acl</artifactId>
<version>4.9.7</version>
</dependency>
Step 2: Generate a Message
DefaultMQProducer producer = new DefaultMQProducer(
groupName,
new AclClientRPCHook(new SessionCredentials(accessKey, secretKey))
);
producer.setNamesrvAddr(nameserver);
producer.start();
for (int i = 0; i < 10; i++) {
Message msg = new Message(topic_name, ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
SendResult sendResult = producer.send(msg);
System.out.printf("%s%n", sendResult);
}
Step 3: Consume the message
The following code example illustrates the use of Push Consumer. For further details, please refer to the more detailed 4.x documentation.
DefaultMQPushConsumer pushConsumer = new DefaultMQPushConsumer(
groupName,
new AclClientRPCHook(new SessionCredentials(accessKey, secretKey)));
pushConsumer.setNamesrvAddr(nameserver);
pushConsumer.subscribe(topic_name, "*");
pushConsumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
});
pushConsumer.start();
Step 4: View message details
After sending the message, a message ID (messageID) is generated. Developers can then verify this recently sent message on the "Message Query" page as shown below. Additionally, it allows viewing specific details and track information of the message. For more information, please refer to Message Query.
Was this page helpful?