Todos los productos
Search
Centro de documentos

Tablestore:SDK de Java

Última actualización: Sep 11, 2026

El SDK de Tablestore para Java admite operaciones con los modelos de columnas anchas, de series temporales y de mensajes.

Integración rápida

Integre el SDK de Tablestore para Java, desde la configuración del entorno hasta la verificación del cliente.

image

Preparar el entorno

Instale el entorno de ejecución de Java (Java 6 o posterior). Ejecute java -version para comprobarlo.

Instalar el SDK

Utilice la versión más reciente del SDK para asegurar que los ejemplos de código se ejecuten correctamente.

Agregar una dependencia de Maven (recomendado)

Para usar el SDK de Tablestore para Java en un proyecto de Maven, agregue a continuación la dependencia en su archivo pom.xml.

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

Importar paquetes JAR en un proyecto de Eclipse

En proyectos que no usan Maven, importe los paquetes JAR manualmente.

  1. Descargue el paquete del SDK de Java.

  2. Descomprima el paquete.

  3. En Eclipse, haga clic derecho en su proyecto y elija Properties > Java Build Path > Libraries > Add External JARs.

  4. Seleccione el archivo tablestore-5.17.7.jar y todos los archivos JAR de la carpeta lib del paquete descomprimido. Después, haga clic en Open.

  5. Compruebe que los paquetes JAR aparezcan en Libraries y luego haga clic en Apply and Close.

    Nota

    Si usa Java SE 9 o posterior, debe importar los paquetes JAR en Modulepath, dentro de Libraries.

Configurar las credenciales de acceso

Create an AccessKey para su cuenta de Alibaba Cloud o usuario de RAM. Luego, configúrelas como variable de entorno para evitar codificarlas directamente en el código.

Reinicie su IDE, la terminal, otras aplicaciones de escritorio y los servicios en segundo plano después de la configuración para cargar las variables de entorno actualizadas. Para obtener más información sobre otros tipos de credenciales de acceso, consulte Configure access credentials .

Linux

  1. Agregue las variables de entorno al final de ~/.bashrc:

    echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
  2. Aplique los cambios:

    source ~/.bashrc
  3. Compruebe las variables de entorno:

    echo $TABLESTORE_ACCESS_KEY_ID
    echo $TABLESTORE_ACCESS_KEY_SECRET

macOS

  1. Consulte cuál es su shell predeterminado:

    echo $SHELL
  2. Configure las variables según el tipo de shell que utilice:

    Zsh

    1. Agregue las variables de entorno al final de ~/.zshrc:

      echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
    2. Aplique los cambios:

      source ~/.zshrc
    3. Compruebe las variables de entorno:

      echo $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET

    Bash

    1. Agregue las variables de entorno al final de ~/.bash_profile:

      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. Aplique los cambios:

      source ~/.bash_profile
    3. Compruebe las variables de entorno:

      echo $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET

Windows

CMD

  1. Establezca las variables de entorno en CMD:

    setx TABLESTORE_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. Reinicie CMD y compruebe los valores:

    echo %TABLESTORE_ACCESS_KEY_ID%
    echo %TABLESTORE_ACCESS_KEY_SECRET%

PowerShell

  1. Ejecute los siguientes comandos en 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. Compruebe las variables de entorno:

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

Inicializar el cliente

Inicialice un cliente síncrono con una firma V4 y compruebe la conexión mediante la enumeración de las tablas de datos.

El cliente es seguro para subprocesos y gestiona automáticamente los grupos internos de hilos y los recursos de conexión. Comparta una sola instancia entre varios hilos en lugar de crear una por cada hilo o solicitud.
Importante

El acceso por red pública está deshabilitado de forma predeterminada en las instancias nuevas. Para acceder a una instancia a través de Internet, habilítelo en la página Network Management.

Modelo de columnas anchas

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();
            }
        }
    }
}

Modelo de series temporales

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();
            }
        }
    }
}

Configuración del cliente

El SDK de Tablestore para Java admite clientes síncronos y asíncronos. El cliente asíncrono ofrece un mayor rendimiento para cargas de trabajo concurrentes.

Cliente asíncrono

El cliente asíncrono utiliza devoluciones de llamada para procesar los resultados sin bloquear los hilos.

Modelo de columnas anchas

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();
            }
        }
    }
}

Modelo de series temporales

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();
            }
        }
    }
}

Versión de firma

Las firmas V4 están disponibles desde el SDK 5.16.1. Utilizan un algoritmo de cifrado y un mecanismo de firma más robustos para mejorar la seguridad. Actualice a V4 siempre que sea posible. A continuación se muestra el código para inicializar una firma V2.

Modelo de columnas anchas

Síncrono

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();
            }
        }
    }
}

Asíncrono

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();
            }
        }
    }
}

Modelo de series temporales

Síncrono

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();
            }
        }
    }
}

Asíncrono

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();
            }
        }
    }
}

Compatibilidad de versiones

La versión más reciente es la 5.x.x. La compatibilidad con versiones anteriores es la siguiente:

  • Los SDK de la serie 4.x.x son compatibles.

  • SDK de Tablestore para Java V2.x.x: no compatible.

Preguntas frecuentes

¿Qué debo hacer si ocurre un conflicto de dependencias de la biblioteca PB al usar el SDK?

Si aparece java.lang.ExceptionInInitializerError, es probable que su proyecto tenga un conflicto de dependencias con la biblioteca Protocol Buffers (PB). Resuélvalo siguiendo PB library conflicts when using the Java SDK.

¿Qué debo hacer si aparece la excepción "Signature mismatch" al usar el SDK?

Se presenta a continuación la excepción:

Error Code: OTSAuthFailed, Message: Signature mismatch., RequestId: 0005f55a-xxxx-xxxx-xxxx-xxxxxxxxxxxx, TraceId: 10b0f0e0-xxxx-xxxx-xxxx-xxxxxxxxxxxx, HttpStatus: 403
  • Causa: el AccessKey ID o el AccessKey secret son incorrectos.

  • Solución: proporcione el AccessKey ID y el AccessKey secret correctos.

¿Qué debo hacer si aparece la excepción "Request denied by instance ACL policies" al usar el SDK?

El SDK puede devolver el error Request denied by instance ACL policies:

[ErrorCode]:OTSAuthFailed, [Message]:Request denied by instance ACL policies., [RequestId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [TraceId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [HttpStatus:]403
  • Causa: el tipo de red del cliente no coincide con la política de acceso de la instancia. Por ejemplo, la instancia no permite el acceso desde Internet.

  • Solución: el acceso por red pública está deshabilitado de forma predeterminada. Para habilitarlo:

    1. En la consola de Tablestore, haga clic en la instancia de destino.

    2. Haga clic en Network Management. En Allowed Network Type, seleccione Internet y luego haga clic en Settings.

¿Qué debo hacer si aparece la excepción "Request denied because this instance can only be accessed from the binded VPC" al usar el SDK?

El SDK puede devolver el error Request denied because this instance can only be accessed from the bound VPC:

[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
  • Causa: el tipo de acceso de la instancia está configurado como Bound VPCs Only o Tablestore Console or Bound VPCs, pero el cliente no se encuentra en una VPC adjunta o no accede a Tablestore mediante un endpoint de VPC.

  • Solución: permita el acceso desde Internet, o bien adjunte una VPC y conecte el cliente desde ella:

    1. En la consola de Tablestore, haga clic en la instancia de destino.

    2. Haga clic en Network Management > Bind VPC. Seleccione un VPC ID y un VSwitch, introduzca un VPC Name y luego haga clic en OK.

¿Qué debo hacer si ocurre una SocketTimeoutException al usar el SDK?

Los tiempos de espera del cliente pueden deberse a fallas de red, inestabilidad, alta carga del servidor o una recolección de basura completa (full GC). Compruebe la conectividad de red, la latencia del servidor y la actividad de recolección de basura. What do I do if a SocketTimeoutException occurs when I use the Java SDK to access Tablestore?.

¿Qué debo hacer si aparece la excepción "The access key id is invalid" al usar el SDK?

Al usar el SDK se presenta a continuación la excepción:

java.lang.IllegalArgumentException: The access key id is invalid:xxx.
  • Causa: el AccessKey, que incluye el AccessKey ID y el AccessKey secret, es incorrecto o contiene un carácter no válido.

  • Solución: proporcione la información correcta del AccessKey.

¿Qué debo hacer si aparece la excepción "java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED" al usar el SDK?

Al usar el SDK se presenta a continuación la excepción:

java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED
  • Causa: ya se llamó al método shutDown, lo cual cerró los reactores de E/S del cliente.

  • Solución: después de ejecutar shutDown, vuelva a inicializar el cliente. Un cliente detenido con shutDown no puede atender nuevas solicitudes.

Referencias