tencent cloud

Java SDK
Last updated:2025-12-24 15:07:56
Java SDK
Last updated: 2025-12-24 15:07:56

Scenarios

This document takes the Java SDK as an example and describes how to use an open-source SDK to send and receive messages, helping you better understand the complete process of sending and receiving messages.

Prerequisites

You have obtained the client connection parameters as instructed in SDK Overview.

Operation Steps

Step 1: Installing the Java Dependency Library

Introduce related dependencies into the Java project. With the Maven project as an example, add the following dependencies to pom.xml:
<dependency>
<groupId>org.apache.pulsar</groupId>
<artifactId>pulsar-client</artifactId>
<version>3.0.8</version>
</dependency>
Note:
It is recommended that 3.0.8 or later versions be used.
If the batch message sending and receiving feature (BatchReceive) is used on the client, use an SDK of 3.0.8 or later versions.

Step 2: Modifying Configuration Parameters

Modify the parameters in Constant.java.
package com.tencent.cloud.tdmq.pulsar;

import org.apache.pulsar.client.api.AuthenticationFactory;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;

public class Constant {
/**
* Service access address on the Cluster page.
*/
private static final String SERVICE_URL = "http://pulsar-xxx.tdmq-pulsar.ap-sh.public.tencenttdmq.com:8080";

/**
* Role token authorized by the namespace to be used on the Role Management page.
*/
private static final String AUTHENTICATION = "eyJrZXlJZC......";


/**
* Initialize the TDMQ for Apache Pulsar client.
*
* @return TDMQ for Apache Pulsar client.
*/
public static PulsarClient initPulsarClient() throws PulsarClientException {
// One TDMQ for Apache Pulsar client corresponds to one client connection.
// In principle, one process has one client. Avoid repeated creation, which consumes resources.
// For use cases about clients and producers/consumers, see the official documentation at https://www.tencentcloud.com/document/product/1179/58090?from_cn_redirect=1.
PulsarClient pulsarClient = PulsarClient.builder()
// Service access address.
.serviceUrl(SERVICE_URL)
// Authorized role token.
.authentication(AuthenticationFactory.token(AUTHENTICATION)).build();
System.out.println(">> pulsar client created.");
return pulsarClient;
}
}

Parameter
Description
SERVICE_URL
Address used to access a cluster. You can view and copy the address from the Cluster page in the console.
AUTHENTICATION
Role token. You can copy the role token from the Role Management page.

Step 3: Producing Messages

Create, compile, and run SimpleProducer.java.
package com.tencent.cloud.tdmq.pulsar.simple;

import com.tencent.cloud.tdmq.pulsar.Constant;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;

import java.nio.charset.StandardCharsets;

/**
* Send messages synchronously.
*/
public class SimpleProducer {

public static void main(String[] args) throws PulsarClientException, InterruptedException {

// Initialize the TDMQ for Apache Pulsar client.
PulsarClient pulsarClient = Constant.initPulsarClient();
// Construct a producer.
Producer<byte[]> producer = pulsarClient.newProducer()
// Full topic path, in the format of persistent://cluster (tenant) ID/namespace/topic name.
.topic("persistent://pulsar-xxx/sdk_java/topic1").create();
System.out.println(">> pulsar producer created.");
for (int i = 0; i < 10; i++) {
String value = "my-sync-message-" + i;
// Send messages.
MessageId msgId = producer.newMessage().key("key" + i).value(value.getBytes(StandardCharsets.UTF_8)).send();
System.out.println("deliver msg " + msgId + ",value:" + value);

Thread.sleep(500);
}
// Disable the producer.
producer.close();
// Disable the client.
pulsarClient.close();
}
}

.topic: Specify the name of the created topic. You should enter the full path in the format of persistent://clusterid/namespace/Topic, and the clusterid/namespace/topic part can be copied from the Topic page in the console.

Step 4: Consuming Messages

Create, compile, and run SimpleConsumer.java.
package com.tencent.cloud.tdmq.pulsar.simple;

import com.tencent.cloud.tdmq.pulsar.Constant;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.SubscriptionInitialPosition;
import org.apache.pulsar.client.api.SubscriptionType;

/**
* Consumer.
*/
public class SimpleConsumer {


public static void main(String[] args) throws PulsarClientException {
// Initialize the TDMQ for Apache Pulsar client.
PulsarClient pulsarClient = Constant.initPulsarClient();
// Construct a consumer.
Consumer<byte[]> consumer = pulsarClient.newConsumer()
// Full topic path, in the format of persistent://cluster (tenant) ID/namespace/topic name, copied from the Topic page.
.topic("persistent://pulsar-xxx/sdk_java/topic1")
// You need to create a subscription on the topic details page in the console. Specify the subscription name here.
.subscriptionName("sub1_topic1")
// Declare the consumption mode to be the Exclusive mode.
.subscriptionType(SubscriptionType.Exclusive)
// Configure consumption from the earliest time. Otherwise, historical messages may not be consumed.
.subscriptionInitialPosition(SubscriptionInitialPosition.Earliest).subscribe();
System.out.println(">> pulsar consumer created.");
for (int i = 0; i < 10; i++) {
// Receive a message corresponding to the current offset.
Message<byte[]> msg = consumer.receive();
MessageId msgId = msg.getMessageId();
String value = new String(msg.getValue());
System.out.println("receive msg " + msgId + ",value:" + value);
// After the message is received, it must be acknowledged. Otherwise, the offset remains at the current message, resulting in message backlogs.
consumer.acknowledge(msg);
}
// Disable the consumer.
consumer.close();
// Disable the client.
pulsarClient.close();
}
}

.topic: Enter the full path of the topic name in the format of persistent://clusterId/namespace/Topic. The clusterid/namespace/topic part can be copied from the Topic page in the console.

.subscriptionName: Specify the subscription name, which can be viewed on the Consumer page.

Step 5: Viewing the Consumption Status

Go to the Message Query page to view message details.
Note:
Only the message trace of a single message can be queried at a time. If the batch feature is enabled on the producer side, only the message trace of the first message within a batch is queried.

The following figure shows the message trace.



Note:
The above is a brief introduction to the publishing and subscription of messages. For more information, see Demo or Pulsar Official Documentation.

Notes Related to SDK Versions

Community Issues and Optimizations

For clients using Java SDK 2.7.2 and earlier versions, it is strongly recommended that they be upgraded to 3.0.8 or later versions. Clients of later versions have fixed the following critical issues:
1. Fixed the issue where broker restarts cause a consumption surge for the consumer (Reference Documentation).
2. Fixed the issue where consumers lose message acknowledgments due to race conditions in batch message acknowledgment (Reference Documentation).
3. Fixed the issue where producers/consumers stop reconnecting or publishing/subscription due to race conditions in I/O threads (Reference Documentation).
4. Fixed the issue of non-standard names for created retry queues and dead letter queues (Reference Documentation).
5. Fixed the issue where all batch messages are repushed because they are unacknowledged (Reference Documentation).
For a complete list of community issues, see Reference Documentation.

Risks in Earlier Versions

For Java SDK 2.7.x and earlier versions, the exception handling in extreme scenarios is not comprehensive enough. In situations such as broker upgrades, restarts, or network failures, there is a very small probability of exceptions during the client and server reconnection process, leading to issues such as sending timeouts or consumption halts.
It is strongly recommended that you upgrade the client to 3.0.8 or later versions before updating the broker cluster version.
In addition, in 2.7.x, 2.9.x, and later versions, the default formats of the retry and dead letter queues are changed. It is recommended that the names of the legacy retry and dead letter queues be specified in the business code for compatibility. Otherwise, messages in the legacy retry/dead letter queues cannot be consumed. For details, see Message Retry and Dead Letter Mechanisms.

Handling Risks in Earlier Versions

New version clients can reconnect normally during broker upgrades, ensuring minimal impact on business operations. However, if your client SDK cannot be upgraded to the new version, it is recommended that you monitor the client's log output and production/consumption metrics in the console after upgrading the broker cluster.
If production or consumption becomes stuck, restart the client promptly. Typically, the client should resume normal operation after restarting. However, a small amount of duplicate production/consumption messages may occur. If the issue persists after you restart the client, submit a ticket promptly for further troubleshooting.
Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback