tencent cloud

Feedback

Use SDK for TDMQ 5.x to Send/Receive General Messages

Last updated: 2024-01-17 17:44:44

    Operation Scenarios

    In calling 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

    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:
    <dependencies>
    <dependency>
    <groupId>org.apache.rocketmq</groupId>
    <artifactId>rocketmq-client-java</artifactId>
    <version>5.0.5</version>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.7</version>
    </dependency>
    </dependencies>

    Step 2: Generate a Message

    public class NormalMessageSyncProducer {
    private static final Logger log = LoggerFactory.getLogger(NormalMessageSyncProducer.class);
    
    private NormalMessageSyncProducer() {
    }
    
    public static void main(String[] args) throws ClientException, IOException {
    final ClientServiceProvider provider = ClientServiceProvider.loadService();
    
    // Add the configuration's ak and sk.
    String accessKey = "yourAccessKey"; //ak
    String secretKey = "yourSecretKey"; //sk
    SessionCredentialsProvider sessionCredentialsProvider =
    new StaticSessionCredentialsProvider(accessKey, secretKey);
    
    // Enter the service access address provided by Tencent Cloud.
    String endpoints = "rmq-xxx.rocketmq.xxxtencenttdmq.com:8081";
    ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
    .setEndpoints(endpoints)
    .enableSsl(false)
    .setCredentialProvider(sessionCredentialsProvider)
    .build();
    String topic = "yourNormalTopic";
    // In most case, you don't need to create too many producers, singleton pattern is recommended.
    final Producer producer = provider.newProducerBuilder()
    .setClientConfiguration(clientConfiguration)
    // Set the topic name(s), which is optional but recommended. It makes producer could prefetch the topic
    // route before message publishing.
    .setTopics(topic)
    // May throw {@link ClientException} if the producer is not initialized.
    .build();
    // Define your message body.
    byte[] body = "This is a normal message for Apache RocketMQ".getBytes(StandardCharsets.UTF_8);
    String tag = "yourMessageTagA";
    final Message message = provider.newMessageBuilder()
    // Set topic for the current message.
    .setTopic(topic)
    // Message secondary classifier of message besides topic.
    .setTag(tag)
    // Key(s) of the message, another way to mark message besides message id.
    .setKeys("yourMessageKey-1c151062f96e")
    .setBody(body)
    .build();
    try {
    final SendReceipt sendReceipt = producer.send(message);
    log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
    } catch (Throwable t) {
    log.error("Failed to send message", t);
    }
    // Close the producer when you don't need it anymore.
    producer.close();
    }
    }

    Step 3: Consume the message

    Tencent Cloud's TDMQ for RocketMQ Version 5.x series supports two consumption modes: Push Consumer and Simple Consumer. The following code example illustrates the use of Push Consumer:
    public class NormalPushConsumer {
    private static final Logger log = LoggerFactory.getLogger(NormalPushConsumer.class);
    
    private NormalPushConsumer() {
    }
    
    public static void main(String[] args) throws ClientException, IOException, InterruptedException {
    final ClientServiceProvider provider = ClientServiceProvider.loadService();
    
    // Add the configuration's ak and sk.
    String accessKey = "yourAccessKey"; //ak
    String secretKey = "yourSecretKey"; //sk
    SessionCredentialsProvider sessionCredentialsProvider =
    new StaticSessionCredentialsProvider(accessKey, secretKey);
    
    // Enter the service access address provided by Tencent Cloud.
    String endpoints = "rmq-xxx.rocketmq.xxxtencenttdmq.com:8081";
    ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
    .setEndpoints(endpoints)
    .enableSsl(false)
    .setCredentialProvider(sessionCredentialsProvider)
    .build();
    String tag = "*";
    FilterExpression filterExpression = new FilterExpression(tag, FilterExpressionType.TAG);
    String consumerGroup = "yourConsumerGroup";
    String topic = "yourTopic";
    // In most case, you don't need to create too many consumers, singleton pattern is recommended.
    PushConsumer pushConsumer = provider.newPushConsumerBuilder()
    .setClientConfiguration(clientConfiguration)
    // Set the consumer group name.
    .setConsumerGroup(consumerGroup)
    // Set the subscription for the consumer.
    .setSubscriptionExpressions(Collections.singletonMap(topic, filterExpression))
    .setMessageListener(messageView -> {
    // Handle the received message and return consume result.
    log.info("Consume message={}", messageView);
    return ConsumeResult.SUCCESS;
    })
    .build();
    // Block the main thread, no need for production environment.
    Thread.sleep(Long.MAX_VALUE);
    // Close the push consumer when you don't need it anymore.
    pushConsumer.close();
    }
    }

    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 the Querying Message section.
    
    
    
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support