Read and write data

Updated at:

Read and write data

  • You can call SDK methods to read and write data. Data can be read from shards in both CLOSED and ACTIVE states, but can only be written to shards in the ACTIVE state.

  • You can also add a dependency on the datahub-client-library, which wraps the Java SDK's read and write capabilities. You can use a producer to write data evenly across shards and a consumer for coordinated consumption. (Recommended)

Read data

There are two ways to read data:

  1. Use the SDK

  2. Use coordinated consumption

    Use the SDK

    Step 1: Get a cursor

    To read data from a topic, you must specify the corresponding shard and the starting read position, represented by a cursor. You can obtain a cursor in one of four ways: OLDEST, LATEST, SEQUENCE, or SYSTEM_TIME.

  • OLDEST: Returns a cursor for the oldest available record.

  • LATEST: Returns a cursor for the most recent record.

  • SEQUENCE: Returns a cursor for the record with a specific sequence number.

  • SYSTEM_TIME: Returns a cursor for the first record at or after a specified timestamp.

    Note

    GetCursorResult getCursor(String projectName, String topicName, String shardId, CursorType type);GetCursorResult getCursor(String projectName, String topicName, String shardId, CursorType type, long param);

  • Parameters

    • projectName The project name.

    • topicName The topic name.

    • shardId The shard ID.

    • CursorType The cursor type.

  • Exceptions

    • DatahubClientException

    • InvalidParameterException

    • AuthorizationFailureException

    • ResourceNotFoundException

    • SeekOutOfRangeException

  • Example code

    public static void getcursor() {
      String shardId = "5";
      try {
          /* Example of using OLDEST */
          String oldestCursor = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.OLDEST).getCursor();
          /* Example of using LATEST */
          String latestCursor = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.LATEST).getCursor();
          /* Example of using SEQUENCE */
          // Get the sequence number of the latest record.
          long seq = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.LATEST).getSequence();
          // Get the cursor to read the last ten records.
          String seqCursor = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.SEQUENCE, seq - 9).getCursor();
          /* Example of using SYSTEM_TIME */
          // Convert the time string to a timestamp.
          String time = "2019-07-01 10:00:00";
          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          long timestamp = 0L;
          try {
              Date date = simpleDateFormat.parse(time);
              timestamp = date.getTime(); // Get the timestamp value.
              //System.out.println(timestamp);
          } catch (ParseException e) {
              System.exit(-1);
          }
          // Get the cursor for reading data recorded after the specified time.
          String timeCursor = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.SYSTEM_TIME, timestamp).getCursor();
          System.out.println("get cursor successful");
      } catch (InvalidParameterException e) {
          System.out.println("Invalid parameter. Please check your parameters.");
          System.exit(1);
      } catch (AuthorizationFailureException e) {
          System.out.println("AK error. Please check your AccessKey ID and AccessKey Secret.");
          System.exit(1);
      } catch (ResourceNotFoundException e) {
          System.out.println("Project, topic, or shard not found.");
          System.exit(1);
      } catch (SeekOutOfRangeException e) {
          System.out.println("Offset is invalid or has expired.");
          System.exit(1);
      } catch (DatahubClientException e) {
          System.out.println("An unknown error occurred.");
          System.out.println(e);
          System.exit(1);
      }
    }

Step 2: Read data

Note

GetRecordsResult getRecords(String projectName, String topicName, String shardId, String cursor, int limit);GetRecordsResult getRecords(String projectName, String topicName, String shardId, RecordSchema schema, String cursor, int limit);

  • Parameters

    • projectName The project name.

    • topicName The topic name.

    • shardId The shard ID.

    • schema This parameter is required if you read TUPLE records.

    • cursor The cursor that specifies the starting position for reading data.

    • limit The maximum number of records to read.

  • Exceptions

    • DatahubClientException

    • InvalidParameterException

    • AuthorizationFailureException

    • ResourceNotFoundException

    • ShardSealedException

    • LimitExceededException

  • Example

1). Read data from a TUPLE topic

public static void example() {
     // The maximum number of records to read in each batch.
     int recordLimit = 1000;
     String shardId = "7";
     // Get a cursor. Here, we get a cursor for the oldest available record.
     // Note: Typically, you only need to call getCursor once at initialization. For subsequent reads, use the nextCursor from the getRecords result.
     String cursor = "";
     try {
         cursor = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.OLDEST).getCursor();
     } catch (InvalidParameterException e) {
         System.out.println("Invalid parameter. Please check your parameters.");
         System.exit(1);
     } catch (AuthorizationFailureException e) {
         System.out.println("AK error. Please check your AccessKey ID and AccessKey Secret.");
         System.exit(1);
     } catch (ResourceNotFoundException e) {
         System.out.println("Project, topic, or shard not found.");
         System.exit(1);
     } catch (SeekOutOfRangeException e) {
         System.out.println("Offset is invalid or has expired.");
         System.exit(1);
     } catch (DatahubClientException e) {
         System.out.println("An unknown error occurred.");
         System.out.println(e);
         System.exit(1);
     }
     while (true) {
         try {
             GetRecordsResult result = datahubClient.getRecords(Constant.projectName, Constant.topicName, shardId, recordSchema, cursor, recordLimit);
             if (result.getRecordCount() <= 0) {
                 // No data found. Sleep and then try again.
                 Thread.sleep(10000);
                 continue;
             }
             for (RecordEntry entry : result.getRecords()) {
                 TupleRecordData data = (TupleRecordData) entry.getRecordData();
                 System.out.println("field1:" + data.getField("field1") + "\t"
                         + "field2:" + data.getField("field2"));
             }
             // Get the next cursor.
             cursor = result.getNextCursor();
         } catch (InvalidCursorException ex) {
             // The cursor is invalid or has expired. Reset the position by getting a new cursor to resume consumption.
             cursor = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.OLDEST).getCursor();
         } catch (SeekOutOfRangeException e) {
             System.out.println("Invalid offset.");
             System.exit(1);
         } catch (ResourceNotFoundException e) {
             System.out.println("Project, topic, or shard not found.");
             System.exit(1);
         } catch (ShardSealedException e) {
             System.out.println("The shard is closed. All data has been read.");
             System.exit(1);
         } catch (LimitExceededException e) {
             System.out.println("Limit may have been exceeded. Please retry.");
         } catch (DatahubClientException e) {
             System.out.println("An unknown error occurred.");
             System.out.println(e);
             System.exit(1);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
     }
 }

2). Read data from a BLOB topic

public static void example() {
    // The maximum number of records to read in each batch.
    int recordLimit = 1000;
    String shardId = "7";
    // Get a cursor. Here, we get a cursor for the oldest available record.
    // Note: Typically, you only need to call getCursor once at initialization. For subsequent reads, use the nextCursor from the getRecords result.
    String cursor = "";
    try {
        cursor = datahubClient.getCursor(Constant.projectName, Constant.blobTopicName, shardId, CursorType.OLDEST).getCursor();
    } catch (InvalidParameterException e) {
        System.out.println("Invalid parameter. Please check your parameters.");
        System.exit(1);
    } catch (AuthorizationFailureException e) {
        System.out.println("AK error. Please check your AccessKey ID and AccessKey Secret.");
        System.exit(1);
    } catch (ResourceNotFoundException e) {
        System.out.println("Project, topic, or shard not found.");
        System.exit(1);
    } catch (SeekOutOfRangeException e) {
        System.out.println("Offset is invalid or has expired.");
        System.exit(1);
    } catch (DatahubClientException e) {
        System.out.println("An unknown error occurred.");
        System.out.println(e);
        System.exit(1);
    }
    while (true) {
        try {
            GetRecordsResult result = datahubClient.getRecords(Constant.projectName, Constant.blobTopicName, shardId, recordSchema, cursor, recordLimit);
            if (result.getRecordCount() <= 0) {
                // No data found. Sleep and then try again.
                Thread.sleep(10000);
                continue;
            }
            /* Consume data */
            for (RecordEntry record: result.getRecords()){
                 BlobRecordData data = (BlobRecordData) record.getRecordData();
                 System.out.println(new String(data.getData()));
            }
            // Get the next cursor.
            cursor = result.getNextCursor();
        } catch (InvalidCursorException ex) {
            // The cursor is invalid or has expired. Reset the position by getting a new cursor to resume consumption.
            cursor = datahubClient.getCursor(Constant.projectName, Constant.blobTopicName, shardId, CursorType.OLDEST).getCursor();
        } catch (SeekOutOfRangeException e) {
            System.out.println("Invalid offset.");
            System.exit(1);
        } catch (ResourceNotFoundException e) {
            System.out.println("Project, topic, or shard not found.");
            System.exit(1);
        } catch (ShardSealedException e) {
            System.out.println("The shard is closed. All data has been read.");
            System.exit(1);
        } catch (LimitExceededException e) {
            System.out.println("Limit may have been exceeded. Please retry.");
        } catch (DatahubClientException e) {
            System.out.println("An unknown error occurred.");
            System.out.println(e);
            System.exit(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Use coordinated consumption

Step 1: Initialize the consumer

Configuration

Parameter

Description

autoCommit

Specifies whether to automatically commit the offset. The default is true. If true, a background thread commits the offset at a set interval, and each read() call confirms that all previously read records have been processed. If set to false, you must acknowledge each record after processing it. The background commit process ensures that all records before the committed offset have been acknowledged.

offsetCommitTimeoutMs

The offset commit interval in milliseconds. Default: 30000. Range: [3000, 300000].

sessionTimeoutMs

The session timeout in milliseconds. The heartbeat interval is set to two-thirds of this value. If no heartbeat is received within the timeout period, the server considers the client stopped and reassigns its shards. Default: 60000. Range: [60000, 180000].

fetchSize

The number of records to read asynchronously from a single shard. The buffer caches twice this number of records. An asynchronous task is triggered to fetch more records when the buffer contains less than twice this value. Default: 1000. Must be greater than 0.

You also need to configure your AccessKey ID and AccessKey Secret in your project. We recommend using environment variables in the configuration file.

datahub.endpoint=<yourEndpoint>
datahub.accessId=<yourAccessKeyId>
datahub.accessKey=<yourAccessKeySecret>
Important

An Alibaba Cloud account's AccessKey grants full access to all APIs. We recommend using a RAM user for API calls and daily O&M.

We strongly recommend against hardcoding your AccessKey ID and AccessKey Secret into your project code. Doing so can lead to key leakage, which compromises the security of all resources under your account.

{
				@Value("${datahub.endpoint}")
				String endpoint ;
				@Value("${datahub.accessId}")
				String accessId;
				@Value("${datahub.accessKey}")
				String accessKey;
        // The endpoint for the China (Hangzhou) region is used as an example. Replace it with the endpoint for your actual region.
        String projectName = "<YourProjectName>";
        String topicName = "<YourTopicName>";
        String subId = "<YourSubscriptionId>";
        /**
         * 1. Use coordinated consumption with the offset service.
         *
         * Coordinated consumption:
         * If two machines use the same subscription ID to consume data from a topic (with 5 shards),
         * you do not need to manually assign shards to each machine. The server automatically distributes them.
         * If a third machine joins, the server rebalances the load.
         *
         * Using the offset service:
         * Data is consumed based on the offset recorded on the server for the subscription ID.
         * If it is a new subscription with no offset, consumption starts from the beginning.
         * To start reading from a specific point in time, you can reset the offset for the subscription ID in the console.
         * 
         * */
        ConsumerConfig config = new ConsumerConfig(endpoint, accessId, accessKey);
        Consumer consumer = new Consumer(projectName, topicName, subId, config);



        /**
         * 2. Use the offset service without coordinated consumption. Provide a subscription ID and a list of shards for the consumer to read.
         *
         * Without coordinated consumption:
         * If two machines use the same subscription ID to consume data from a topic (with 5 shards), you must manually
         * assign which shards each machine consumes (for example, Client A consumes shards 0, 1, and 2; Client B consumes shards 3 and 4).
         * If a third machine joins, you must redefine the consumption strategy yourself.
         * 
         * */

        // Example for Client A, which consumes shards 0, 1, and 2:
        List<String> shardlists = Arrays.asList("0", "1", "2");
        ConsumerConfig config = new ConsumerConfig(endpoint, accessId, accessKey);
        Consumer consumer = new Consumer(projectName, topicName, subId, shardlists, config);


        // Example for Client B, which consumes shards 3 and 4:
//        List<String> shardlists = Arrays.asList("3", "4");
//        ConsumerConfig config = new ConsumerConfig(endpoint, accessId, accessKey);
//        Consumer consumer = new Consumer(projectName, topicName, subId, shardlists, config);



        /**
         * 3. Do not use coordinated consumption or the offset service.
         *
         * Without the offset service:
         * You must use your own storage (such as a database or Redis) to track the offset (by time or sequence) for each shard.
         * Each time you read data, you must initialize the consumer with your recorded offset.
         * 
         * */
        Map<String, Offset> offsetMap = new HashMap<>();
// Provide a sequence and a timestamp. If the sequence is out of range, the timestamp is used to get the cursor.
        offsetMap.put("0", new Offset(100, 1548573440756L));
// Provide only a sequence. The cursor is retrieved based on the sequence.
        offsetMap.put("1", new Offset().setSequence(1));
// Provide only a timestamp. The cursor is retrieved based on the timestamp.
        offsetMap.put("2", new Offset().setTimestamp(1548573440756L));
        ConsumerConfig config = new ConsumerConfig(endpoint, accessId, accessKey);
        Consumer consumer = new Consumer(projectName, topicName, subId, offsetMap, config);
    }

Step 2: Coordinated consumption example

import com.aliyun.datahub.client.exception.AuthorizationFailureException;
import com.aliyun.datahub.client.exception.DatahubClientException;
import com.aliyun.datahub.client.exception.InvalidParameterException;
import com.aliyun.datahub.client.exception.NoPermissionException;
import com.aliyun.datahub.client.exception.SubscriptionOfflineException;
import com.aliyun.datahub.client.exception.SubscriptionOffsetResetException;
import com.aliyun.datahub.client.exception.SubscriptionSessionInvalidException;
import com.aliyun.datahub.client.model.RecordEntry;
import com.aliyun.datahub.client.model.TupleRecordData;
import com.aliyun.datahub.clientlibrary.config.ConsumerConfig;
import com.aliyun.datahub.clientlibrary.consumer.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class DatahubReader {
    private static final Logger LOG = LoggerFactory.getLogger(DatahubReader.class);

    private static void sleep(long milliSeconds) {
        try {
            TimeUnit.MILLISECONDS.sleep(milliSeconds);
        } catch (InterruptedException e) {
            // TODO: Handle this exception.
        }
    }

    public static Consumer createConsumer(ConsumerConfig config, String project, String topic, String subId)
    {
        return new Consumer(project, topic, subId, config);
    }

    public static void main(String[] args) {
        String projectName = "<YourProjectName>";
        String topicName = "<YourTopicName>";
        String subId = "<YourSubscriptionId>";

        ConsumerConfig config = new ConsumerConfig(endpoint, accessId, accessKey);
        Consumer consumer = createConsumer(config, projectName, topicName, subId);

        int maxRetry = 3;
        boolean stop = false;
        try {
            while (!stop) {
                try {
                    while (true) {
                        // After initializing a coordinated consumer, you must wait about 40 seconds for the server to assign shards. During this period, the read method returns null.
                        // In auto-commit mode, each call to read() assumes that previously read data has been processed and automatically acknowledges it.
                        RecordEntry record = consumer.read(maxRetry);

                        // Process the data.
                        if (record != null) {
                            TupleRecordData data = (TupleRecordData) record.getRecordData();
                            // Process the data based on your schema. This example prints the content of the first column.
                            LOG.info("field1: {}", data.getField(0));

                            // Get data by column name.
                            // LOG.info("field2: {}", data.getField("field2"));

                            // In manual commit mode, you must acknowledge each record after processing.
                            // In auto-commit mode, the ack() method does nothing.
                            // Available in version 1.1.7 and later.
                            record.getKey().ack();
                        } else {
                            LOG.info("read null");
                        }
                    }
                } catch (SubscriptionOffsetResetException e) {
                    // The offset was reset. Re-initialize the consumer.
                    try {
                        consumer.close();
                        consumer = createConsumer(config, projectName, topicName, subId);
                    } catch (DatahubClientException e1) {
                        // Initialization failed. Retry or throw the exception.
                        LOG.error("create consumer failed", e);
                        throw e;
                    }
                } catch (InvalidParameterException |
                        SubscriptionOfflineException |
                        SubscriptionSessionInvalidException |
                        AuthorizationFailureException |
                        NoPermissionException e) {
                    // Invalid request parameter.
                    // The subscription is offline.
                    // The same shard in the subscription is occupied by another client.
                    // The signature is incorrect.
                    // You do not have the required permissions.
                    LOG.error("read failed", e);
                    throw e;
                } catch (DatahubClientException e) {
                    // Base exception class, which includes network issues. You can choose to retry.
                    LOG.error("read failed, retry", e);
                    sleep(1000);
                }
            }
        } catch (Throwable e) {
            LOG.error("read failed", e);
        } finally {
            // Ensure that resources are released correctly.
            // This will commit the acknowledged offsets.
            consumer.close();
        }
    }
}

Write data

Use the SDK

Server versions 2.12 and later support the PutRecordsByShard interface. For earlier versions, use the putRecords interface. When using putRecordsByShard, you must specify the shard to write to; otherwise, DataHub writes data to the first ACTIVE shard by default. In both methods, the records parameter is a List of records. All records in the list must be of the same type, either TUPLE or BLOB. DataHub currently supports writing by shard (server >= 2.12) and mixed writing, which use the putRecordsByShard and putRecords interfaces, respectively. With putRecords, you must check the PutRecordsResult to confirm successful writes. In contrast, the putRecordsByShard interface reports success or failure directly through exceptions. If your server supports it, we recommend using the putRecordsByShard interface.

Note

PutRecordsResult putRecords(String projectName, String topicName, List records);PutRecordsByShardResult putRecordsByShard(String projectName, String topicName, String shardId, List records);

  • Parameters

    • projectName The project name.

    • topicName The topic name.

    • shardId The shard ID.

    • records The list of records to write.

  • Exceptions

    • DatahubClientException

    • InvalidParameterException

    • AuthorizationFailureException

    • ResourceNotFoundException

    • ShardSealedException

    • LimitExceededException

1). Write to a TUPLE topic

// Write TUPLE data
public static void tupleExample() {
    String shardId = "9";
    // Get the schema.
    recordSchema = datahubClient.getTopic(Constant.projectName, Constant.topicName).getRecordSchema();
    // Generate ten records.
    List<RecordEntry> recordEntries = new ArrayList<>();
    for (int i = 0; i < 10; ++i) {
        RecordEntry recordEntry = new RecordEntry();
        // You can set custom attributes for each record, such as an IP address or machine name. This is optional and does not affect the write operation.
        recordEntry.addAttribute("key1", "value1");
        TupleRecordData data = new TupleRecordData(recordSchema);
        data.setField("field1", "HelloWorld");
        data.setField("field2", 1234567);
        recordEntry.setRecordData(data);
        recordEntry.setShardId(shardId);
        recordEntries.add(recordEntry);
    }
    try {
        // Supported on server versions 2.12 and later. For earlier versions, use the putRecords interface.
        //datahubClient.putRecordsByShard(Constant.projectName, Constant.topicName, shardId, recordEntries);
        datahubClient.putRecords(Constant.projectName, Constant.topicName, recordEntries);
        System.out.println("write data successful");
    } catch (InvalidParameterException e) {
        System.out.println("Invalid parameter. Please check your parameters.");
        System.exit(1);
    } catch (AuthorizationFailureException e) {
        System.out.println("AK error. Please check your AccessKey ID and AccessKey Secret.");
        System.exit(1);
    } catch (ResourceNotFoundException e) {
        System.out.println("Project, topic, or shard not found.");
        System.exit(1);
    } catch (ShardSealedException e) {
        System.out.println("The shard status is CLOSED and cannot be written to.");
        System.exit(1);
    } catch (DatahubClientException e) {
        System.out.println("An unknown error occurred.");
        System.out.println(e);
        System.exit(1);
    }
}

2). Write to a BLOB topic

// Write BLOB data
public static void blobExample() {
    // Generate ten records.
    List<RecordEntry> recordEntries = new ArrayList<>();
    String shardId = "4";
    for (int i = 0; i < 10; ++i) {
        RecordEntry recordEntry = new RecordEntry();
        // Set custom attributes for each record.
        recordEntry.addAttribute("key1", "value1");
        BlobRecordData data = new BlobRecordData("123456".getBytes(Charsets.UTF_8));
        recordEntry.setRecordData(data);
        recordEntry.setShardId(shardId);
        recordEntries.add(recordEntry);
        recordEntry.setShardId("0");
    }
    while (true) {
        try {
            // Supported on server versions 2.12 and later. For earlier versions, use the putRecords interface.
            //datahubClient.putRecordsByShard(Constant.projectName, Constant.topicName, shardId, recordEntries);
            datahubClient.putRecords(Constant.projectName, Constant.topicName, recordEntries);
            System.out.println("write data successful");
            break;
        } catch (InvalidParameterException e) {
            System.out.println("Invalid parameter. Please check your parameters.");
            System.exit(1);
        } catch (AuthorizationFailureException e) {
            System.out.println("AK error. Please check your AccessKey ID and AccessKey Secret.");
            System.exit(1);
        } catch (ResourceNotFoundException e) {
            System.out.println("Project, topic, or shard not found.");
            System.exit(1);
        } catch (ShardSealedException e) {
            System.out.println("The shard status is CLOSED and cannot be written to.");
            System.exit(1);
        } catch (LimitExceededException e) {
            System.out.println("QPS limit may be exceeded. Please retry.");
        } catch (DatahubClientException e) {
            System.out.println("An unknown error occurred.");
            System.out.println(e);
            System.exit(1);
        }
    }
}

Use a producer

Step 1: Add dependencies

<dependency>
    <groupId>com.aliyun.datahub</groupId>
    <artifactId>aliyun-sdk-datahub</artifactId>
    <version>2.19.0-public</version>
</dependency>
<dependency>
      <groupId>com.aliyun.datahub</groupId>
      <artifactId>datahub-client-library</artifactId>
      <version>1.1.12-public</version>
</dependency>

Step 2: Code example

import com.aliyun.datahub.client.exception.AuthorizationFailureException;
import com.aliyun.datahub.client.exception.DatahubClientException;
import com.aliyun.datahub.client.exception.InvalidParameterException;
import com.aliyun.datahub.client.exception.MalformedRecordException;
import com.aliyun.datahub.client.exception.NoPermissionException;
import com.aliyun.datahub.client.exception.ShardNotFoundException;
import com.aliyun.datahub.client.model.Field;
import com.aliyun.datahub.client.model.FieldType;
import com.aliyun.datahub.client.model.RecordEntry;
import com.aliyun.datahub.client.model.RecordSchema;
import com.aliyun.datahub.client.model.TupleRecordData;
import com.aliyun.datahub.clientlibrary.config.ProducerConfig;
import com.aliyun.datahub.clientlibrary.producer.Producer;
import com.aliyun.datahub.exception.ResourceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class DatahubWriter {
    private static final Logger LOG = LoggerFactory.getLogger(DatahubWriter.class);

    private static void sleep(long milliSeconds) {
        try {
            TimeUnit.MILLISECONDS.sleep(milliSeconds);
        } catch (InterruptedException e) {
            // TODO: Handle this exception.
        }
    }

    private static List<RecordEntry> genRecords(RecordSchema schema) {
        List<RecordEntry> recordEntries = new ArrayList<>();
        for (int cnt = 0; cnt < 10; ++cnt) {
            RecordEntry entry = new RecordEntry();

            entry.addAttribute("key1", "value1");
            entry.addAttribute("key2", "value2");

            TupleRecordData data = new TupleRecordData(schema);
            data.setField("field1", "testValue");
            data.setField("field2", 1);

            entry.setRecordData(data);
            recordEntries.add(entry);
        }
        return recordEntries;
    }

    private static void sendRecords(Producer producer, List<RecordEntry> recordEntries) {
        int maxRetry = 3;
        while (true) {
            try {
                // Automatically select a shard to write to.
                producer.send(recordEntries, maxRetry);

                // Or specify a shard to write to, for example, "0".
                // producer.send(recordEntries, "0", maxRetry);
                LOG.error("send records: {}", recordEntries.size());
                break;
            } catch (MalformedRecordException e) {
                // The record format is invalid. Ignore or throw an exception based on your use case.
                LOG.error("write fail", e);
                throw e;
            } catch (InvalidParameterException |
                    AuthorizationFailureException |
                    NoPermissionException e) {
                // Invalid request parameter.
                // The signature is incorrect.
                // You do not have the required permissions.
                LOG.error("write fail", e);
                throw e;
            } catch (ShardNotFoundException e) {
                // The shard was not found. This can be ignored if you are not writing to a self-specified shard.
                LOG.error("write fail", e);
                sleep(1000);
            } catch (ResourceNotFoundException e) {
                // The project, topic, or shard was not found.
                LOG.error("write fail", e);
                throw e;
            } catch (DatahubClientException e) {
                // Base exception class, which includes network issues. You can choose to retry.
                LOG.error("write fail", e);
                sleep(1000);
            }
        }
    }

    public static void main(String[] args) {
        String projectName = "<YourProjectName>";
        String topicName = "<YourTopicName>";

        RecordSchema schema =  datahubClient.getTopic(projectName, topicName).getRecordSchema();



        ProducerConfig config = new ProducerConfig(endpoint, accessId, accessKey);
        Producer producer = new Producer(projectName, topicName, config);

        // Control the loop based on your use case.
        boolean stop = false;
        try {
            while (!stop) {
                List<RecordEntry> recordEntries = genRecords(schema);
                sendRecords(producer, recordEntries);
            }
        } finally {
            // Ensure that resources are released correctly.
            producer.close();
        }
    }
}

Multiple write methods

In DataHub versions earlier than 2.12, only the putRecords interface was supported. The RecordEntry class contains three attributes: shardId, partitionKey, and hashKey. By setting these attributes, you can determine to which shard the data is written. Note: Writing data by using a partitionKey or hashKey is not supported when shard extension mode is enabled.

Note

For versions 2.12 and later, we recommend using the putRecordsByShard interface to avoid performance loss caused by server-side partitioning.

1). Write by ShardID This is the recommended method. Example:

RecordEntry entry = new RecordEntry();
entry.setShardId("0");

2). Write by HashKey Specify a 128-bit MD5 value. When writing by HashKey, the system determines the target shard based on the shard's Shard operations. Example:

RecordEntry entry = new RecordEntry();
entry.setHashKey("7FFFFFFFFFFFFFFD7FFFFFFFFFFFFFFD");

3). Write by partition key Specify a string as the partition key. The system uses the MD5 value of this string and the shard's Shard operations to determine the target shard. Example:

RecordEntry entry = new RecordEntry();
entry.setPartitionKey("TestPartitionKey");

Notes

consumer and producer objects are not thread-safe. If you need to use multiple threads, create a separate consumer or producer object for each thread.