All Products
Search
Document Center

Tablestore:Java SDK

Last Updated:Dec 03, 2025

The Tablestore Java SDK supports operations for the wide column, timeseries, and message models. It provides Java developers with comprehensive data storage and management capabilities.

Quick integration

Follow these steps to quickly integrate the Tablestore Java SDK. This guide covers the entire process from preparing the environment to verifying the client connection.

image

Prepare the environment

Download and install the Java runtime environment (Java 6 or later). Run the java -version command to check your Java version.

Install the SDK

Choose an installation method as needed. We recommend that you use the latest SDK version to ensure that the code examples run correctly.

Add a Maven dependency (Recommended)

To use the Tablestore Java SDK in a Maven project, add the following dependency to your pom.xml file.

<dependency>
    <groupId>com.aliyun.openservices</groupId>
    <artifactId>tablestore</artifactId>
    <version>5.17.7</version>
</dependency>

Import JAR packages into an Eclipse project

For projects that do not use Maven, integrate the SDK by manually importing the JAR packages.

  1. Download the Java SDK package.

  2. Unzip the package.

  3. In Eclipse, right-click your project and choose Properties > Java Build Path > Libraries > Add External JARs.

  4. Navigate to the unzipped package folder from Step 2. Select the tablestore-5.17.7.jar file and all JAR files in the lib folder. Click Open to import the JAR packages.

  5. Confirm that all the JAR packages are imported under Libraries. Click Apply and Close to apply the project configuration.

    Note

    If you use Java SE 9 or later, you must import the JAR packages to Modulepath under Libraries.

Configure access credentials

Create an AccessKey for your Alibaba Cloud account or a RAM user. Then, configure the AccessKey in the environment variables as shown below. Configuring the AccessKey in environment variables improves security because it prevents you from hard-coding sensitive information in your code.

After the configuration is complete, you must restart or refresh your development environment. This includes your IDE, command-line interface, other desktop applications, and background services. This ensures that the latest system environment variables are loaded. For more information about other types of access credentials, see Configure access credentials.

Linux

  1. Run the following commands to append the environment variable settings to the ~/.bashrc file.

    echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
  2. Run the following command to apply the changes.

    source ~/.bashrc
  3. Run the following commands to verify that the environment variables are effective.

    echo $TABLESTORE_ACCESS_KEY_ID
    echo $TABLESTORE_ACCESS_KEY_SECRET

macOS

  1. Run the following command in the terminal to view your default shell type.

    echo $SHELL
  2. Perform the following operations based on your default shell type.

    Zsh

    1. Run the following commands to append the environment variable settings to the ~/.zshrc file.

      echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
    2. Run the following command to apply the changes.

      source ~/.zshrc
    3. Run the following commands to verify that the environment variables are effective.

      echo $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET

    Bash

    1. Run the following commands to append the environment variable settings to the ~/.bash_profile file.

      echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
      echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
    2. Run the following command to apply the changes.

      source ~/.bash_profile
    3. Run the following commands to verify that the environment variables are effective.

      echo $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET

Windows

CMD

  1. Run the following commands in Command Prompt (CMD) to set the environment variables.

    setx TABLESTORE_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. Restart CMD and run the following commands to verify that the environment variables are effective.

    echo %TABLESTORE_ACCESS_KEY_ID%
    echo %TABLESTORE_ACCESS_KEY_SECRET%

PowerShell

  1. Run the following commands in PowerShell.

    [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Run the following commands to verify that the environment variables are effective.

    [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Initialize the client

The following examples show how to initialize a synchronous client using a V4 signature. Verify the connection by listing the data tables in the Tablestore instance.

The client is thread-safe and automatically manages internal thread pools and connection resources. In a multi-threaded environment, you should share a single client instance. Do not create a new client object for each thread or request.
Important

By default, public network access is disabled for new instances. To access resources in an instance over the Internet, you must enable public network access on the Network Management page for the instance.

Wide column model

import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.core.auth.V4Credentials;
import com.alicloud.openservices.tablestore.model.ListTableResponse;

public class SyncClientV4 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String region = "cn-hangzhou"; // Specify the region ID of the instance, for example, "cn-hangzhou".
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        SyncClient client = null;
        try {
            // Construct credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // Create a client instance.
            client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // List all data tables.
            ListTableResponse listTableResponse = client.listTable();

            // Print the list of data tables.
            System.out.println("Found " + listTableResponse.getTableNames().size() + " data tables in instance '" + instanceName + "':");

            listTableResponse.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list data tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Timeseries model

import com.alicloud.openservices.tablestore.TimeseriesClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.core.auth.V4Credentials;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;

public class TimeseriesSyncClientV4 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String region = "cn-hangzhou"; // Specify the region ID of the instance, for example, "cn-hangzhou".
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        TimeseriesClient client = null;
        try {
            // Construct V4 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // Create a timeseries client instance.
            client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // List all timeseries tables.
            ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();

            // Print the list of timeseries tables.
            System.out.println("Found " + listTimeseriesTableResponse.getTimeseriesTableNames().size() + " timeseries tables in instance '" + instanceName + "':");

            listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list timeseries tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Client configuration

The Tablestore Java SDK supports synchronous and asynchronous clients. Choose the client type as needed. The asynchronous client provides better concurrent processing capabilities and is suitable for high-throughput scenarios.

Asynchronous client

The asynchronous client uses a callback mechanism to process request results. This avoids thread blocking and improves the concurrent processing capabilities of your application.

Wide column model

import com.alicloud.openservices.tablestore.AsyncClient;
import com.alicloud.openservices.tablestore.TableStoreCallback;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.core.auth.V4Credentials;
import com.alicloud.openservices.tablestore.model.ListTableRequest;
import com.alicloud.openservices.tablestore.model.ListTableResponse;

import java.util.concurrent.*;

public class AsyncClientV4 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String region = "cn-hangzhou"; // Specify the region ID of the instance, for example, "cn-hangzhou".
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        AsyncClient client = null;
        try {
            // Construct V4 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // Create an asynchronous client instance.
            client = new AsyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // Use CompletableFuture for asynchronous processing.
            CompletableFuture<ListTableResponse> future = new CompletableFuture<>();

            // Process the asynchronous result in the callback.
            client.listTable(new TableStoreCallback<ListTableRequest, ListTableResponse>() {
                @Override
                public void onCompleted(ListTableRequest req, ListTableResponse res) {
                    System.out.println("Asynchronous request completed successfully.");
                    future.complete(res); // Complete the Future when the asynchronous operation is successful.
                }
                @Override
                public void onFailed(ListTableRequest req, Exception ex) {
                    System.err.println("Asynchronous request failed.");
                    future.completeExceptionally(ex); // Complete the Future with an exception when the asynchronous operation fails.
                }
            });

            System.out.println("Asynchronous listTable request sent. Waiting for result...");

            // Block and wait for the result, and set a timeout.
            // In practice, continue to execute other non-blocking tasks or pass the future to other processes.
            ListTableResponse response = future.get(5, TimeUnit.SECONDS);

            // Process the successful result in the main thread.
            System.out.println("Found " + response.getTableNames().size() + " data tables in instance '" + instanceName + "':");
            response.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list data tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Timeseries model

import com.alicloud.openservices.tablestore.AsyncTimeseriesClient;
import com.alicloud.openservices.tablestore.TableStoreCallback;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.core.auth.V4Credentials;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableRequest;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;

import java.util.concurrent.*;

public class TimeseriesAsyncClientV4 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String region = "cn-hangzhou"; // Specify the region ID of the instance, for example, "cn-hangzhou".
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        AsyncTimeseriesClient client = null;
        try {
            // Construct V4 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // Create an asynchronous timeseries client instance.
            client = new AsyncTimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // Use CompletableFuture for asynchronous processing.
            CompletableFuture<ListTimeseriesTableResponse> future = new CompletableFuture<>();

            // Process the asynchronous result in the callback.
            client.listTimeseriesTable(new TableStoreCallback<ListTimeseriesTableRequest, ListTimeseriesTableResponse>() {
                @Override
                public void onCompleted(ListTimeseriesTableRequest req, ListTimeseriesTableResponse res) {
                    System.out.println("Asynchronous request completed successfully.");
                    future.complete(res); // Complete the Future when the asynchronous operation is successful.
                }
                @Override
                public void onFailed(ListTimeseriesTableRequest req, Exception ex) {
                    System.err.println("Asynchronous request failed.");
                    future.completeExceptionally(ex); // Complete the Future with an exception when the asynchronous operation fails.
                }
            });

            System.out.println("Asynchronous listTimeseriesTable request sent. Waiting for result...");

            // Block and wait for the result, and set a timeout.
            // In a real-world application, you can continue to execute other non-blocking tasks or pass the future to other processes.
            ListTimeseriesTableResponse response = future.get(5, TimeUnit.SECONDS);

            // Process the successful result in the main thread.
            if (response.getTimeseriesTableNames() != null) {
                System.out.println("Found " + response.getTimeseriesTableNames().size() + " timeseries tables in instance '" + instanceName + "':");
                response.getTimeseriesTableNames().forEach(System.out::println);
            }
        } catch (Exception e) {
            System.err.println("Failed to list timeseries tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Signature version

The Tablestore Java SDK has supported V4 signatures since version 5.16.1. The V4 signature uses a stronger encryption algorithm and signing mechanism to improve security. We recommend that you upgrade your SDK and use the V4 signature. The following code shows how to initialize a client using a V2 signature.

Wide column model

Sync

import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.model.ListTableResponse;

public class SyncClientV2 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        SyncClient client = null;
        try {
            // Construct V2 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // Create a client instance.
            client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // List all data tables.
            ListTableResponse listTableResponse = client.listTable();

            // Print the list of data tables.
            System.out.println("Found " + listTableResponse.getTableNames().size() + " data tables in instance '" + instanceName + "':");

            listTableResponse.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list data tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Asynchronous

import com.alicloud.openservices.tablestore.AsyncClient;
import com.alicloud.openservices.tablestore.TableStoreCallback;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.model.ListTableRequest;
import com.alicloud.openservices.tablestore.model.ListTableResponse;

import java.util.concurrent.*;

public class AsyncClientV2 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        AsyncClient client = null;
        try {
            // Construct V2 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // Create an asynchronous client instance.
            client = new AsyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // Use CompletableFuture for asynchronous processing.
            CompletableFuture<ListTableResponse> future = new CompletableFuture<>();

            // Process the asynchronous result in the callback.
            client.listTable(new TableStoreCallback<ListTableRequest, ListTableResponse>() {
                @Override
                public void onCompleted(ListTableRequest req, ListTableResponse res) {
                    System.out.println("Asynchronous request completed successfully.");
                    future.complete(res); // Complete the Future when the asynchronous operation is successful.
                }
                @Override
                public void onFailed(ListTableRequest req, Exception ex) {
                    System.err.println("Asynchronous request failed.");
                    future.completeExceptionally(ex); // Complete the Future with an exception when the asynchronous operation fails.
                }
            });

            System.out.println("Asynchronous listTable request sent. Waiting for result...");

            // Block and wait for the result, and set a timeout.
            // In practice, continue to execute other non-blocking tasks or pass the future to other processes.
            ListTableResponse response = future.get(5, TimeUnit.SECONDS);

            // Process the successful result in the main thread.
            System.out.println("Found " + response.getTableNames().size() + " data tables in instance '" + instanceName + "':");
            response.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list data tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Timeseries model

Sync

import com.alicloud.openservices.tablestore.TimeseriesClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;

public class TimeseriesSyncClientV2 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        TimeseriesClient client = null;
        try {
            // Construct V2 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // Create a timeseries client instance.
            client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // List all timeseries tables.
            ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();

            // Print the list of timeseries tables.
            System.out.println("Found " + listTimeseriesTableResponse.getTimeseriesTableNames().size() + " timeseries tables in instance '" + instanceName + "':");

            listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list timeseries tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Asynchronous

import com.alicloud.openservices.tablestore.AsyncTimeseriesClient;
import com.alicloud.openservices.tablestore.TableStoreCallback;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableRequest;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;

import java.util.concurrent.*;

public class TimeseriesAsyncClientV2 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        AsyncTimeseriesClient client = null;
        try {
            // Construct V2 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // Create an asynchronous timeseries client instance.
            client = new AsyncTimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // Use CompletableFuture for asynchronous processing.
            CompletableFuture<ListTimeseriesTableResponse> future = new CompletableFuture<>();

            // Process the asynchronous result in the callback.
            client.listTimeseriesTable(new TableStoreCallback<ListTimeseriesTableRequest, ListTimeseriesTableResponse>() {
                @Override
                public void onCompleted(ListTimeseriesTableRequest req, ListTimeseriesTableResponse res) {
                    System.out.println("Asynchronous request completed successfully.");
                    future.complete(res); // Complete the Future when the asynchronous operation is successful.
                }
                @Override
                public void onFailed(ListTimeseriesTableRequest req, Exception ex) {
                    System.err.println("Asynchronous request failed.");
                    future.completeExceptionally(ex); // Complete the Future with an exception when the asynchronous operation fails.
                }
            });

            System.out.println("Asynchronous listTimeseriesTable request sent. Waiting for result...");

            // Block and wait for the result, and set a timeout.
            // In practice, continue to execute other non-blocking tasks or pass the future to other processes.
            ListTimeseriesTableResponse response = future.get(5, TimeUnit.SECONDS);

            // Process the successful result in the main thread.
            if (response.getTimeseriesTableNames() != null) {
                System.out.println("Found " + response.getTimeseriesTableNames().size() + " timeseries tables in instance '" + instanceName + "':");
                response.getTimeseriesTableNames().forEach(System.out::println);
            }
        } catch (Exception e) {
            System.err.println("Failed to list timeseries tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Version compatibility

The latest version is 5.x.x. The compatibility of the latest version with earlier versions is described as follows:

  • The 4.x.x series SDKs are compatible.

  • Tablestore SDK for Java V2.x.x: incompatible

FAQ

What do I do if a PB library dependency conflict occurs when I use the SDK?

If an error such as java.lang.ExceptionInInitializerError occurs when you use the SDK, a Protocol Buffers (PB) library dependency conflict may exist in your project. To resolve this conflict, see PB library conflicts when using the Java SDK.

What do I do if a "Signature mismatch" exception occurs when I use the SDK?

The following exception occurs:

Error Code: OTSAuthFailed, Message: Signature mismatch., RequestId: 0005f55a-xxxx-xxxx-xxxx-xxxxxxxxxxxx, TraceId: 10b0f0e0-xxxx-xxxx-xxxx-xxxxxxxxxxxx, HttpStatus: 403
  • Cause: The AccessKey ID or AccessKey secret specified during client initialization is incorrect.

  • Solution: Provide the correct AccessKey, which includes the AccessKey ID and AccessKey secret.

What do I do if a "Request denied by instance ACL policies" exception occurs when I use the SDK?

The following Request denied by instance ACL policies exception occurs when you use the SDK to access resources in a Tablestore instance. An example error is shown below:

[ErrorCode]:OTSAuthFailed, [Message]:Request denied by instance ACL policies., [RequestId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [TraceId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [HttpStatus:]403
  • Cause: The network type used by the client does not meet the network access requirements of the instance. For example, the client uses the Internet, but the instance is not configured to allow access over the Internet.

  • Solution: By default, public network access is disabled for new instances. To access resources in an instance over the Internet, enable public network access as follows:

    1. Go to the Tablestore console and click the instance alias.

    2. Click Network Management. For Allowed Network Type, select Internet, and then click Settings.

What do I do if a "Request denied because this instance can only be accessed from the binded VPC" exception occurs when I use the SDK?

The following Request denied because this instance can only be accessed from the bound VPC exception occurs when you use the SDK to access resources in a Tablestore instance. An example error is shown below:

[ErrorCode]:OTSAuthFailed, [Message]:Request denied because this instance can only be accessed from the binded VPC., [RequestId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [TraceId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [HttpStatus:]403
  • Cause: If the access type of the Tablestore instance is set to Bound VPCs Only or Tablestore Console or Bound VPCs, you must attach a VPC to the instance. You must also ensure that the client is in the same VPC as the instance and accesses Tablestore using a VPC endpoint.

  • Solution: Change the instance access type to allow Internet access, or attach a VPC to the Tablestore instance and ensure that the client is within that VPC network. To attach a VPC:

    1. Go to the Tablestore console and click the instance alias.

    2. Click Network Management > Bind VPC. Select a VPC ID and a VSwitch, enter a VPC Name, and then click OK.

What do I do if a SocketTimeoutException occurs when I use the SDK?

A client may time out when it accesses Tablestore due to network connection failures, network jitter, high server load, or a full garbage collection (GC) on the client. To resolve this issue, check the network connectivity, server latency, and whether a full GC has occurred on the client. For more information, see What do I do if a SocketTimeoutException occurs when I use the Java SDK to access Tablestore?.

What do I do if a "The access key id is invalid" exception occurs when I use the SDK?

The following exception occurs when you use the SDK:

java.lang.IllegalArgumentException: The access key id is invalid:xxx.
  • Cause: The AccessKey, which includes the AccessKey ID and AccessKey secret, is incorrect or contains an invalid character.

  • Solution: Provide the correct AccessKey information.

What do I do if a "java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED" exception occurs when I use the SDK?

The following exception occurs when you use the SDK:

java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED
  • Cause: The shutDown method was called on the client, and its internal I/O reactors have been closed.

  • Solution: The client cannot be in the shutDown state when it is called. If the client is in the shutDown state, re-initialize it before performing an operation.

References