O Tablestore SDK for Java oferece suporte a operações com os modelos de coluna larga, séries temporais e mensagens.
Integração rápida
Integre o Tablestore SDK for Java, desde a configuração do ambiente até a verificação do cliente.
Prepare o ambiente
Instale o runtime do Java (Java 6 ou posterior). Execute java -version para verificar a instalação.
Instale o SDK
Utilize a versão mais recente do SDK para garantir que os exemplos de código funcionem corretamente.
Adicionar uma dependência do Maven (Recomendado)
Para usar o Tablestore SDK for Java em um projeto Maven, adicione a seguinte dependência ao seu arquivo pom.xml.
<dependency>
<groupId>com.aliyun.openservices</groupId>
<artifactId>tablestore</artifactId>
<version>5.17.7</version>
</dependency>
Importar pacotes JAR para um projeto Eclipse
Em projetos que não utilizam Maven, importe os pacotes JAR manualmente.
Baixe o pacote do SDK para Java.
Descompacte o pacote.
No Eclipse, clique com o botão direito no projeto e escolha .
Selecione o arquivo
tablestore-5.17.7.jare todos os arquivos JAR na pastalibdo pacote descompactado e clique em Open.-
Verifique se os pacotes JAR aparecem em
Librariese clique em Apply and Close.NotaSe você utilizar Java SE 9 ou posterior, será necessário importar os pacotes JAR para
Modulepathdentro deLibraries.
Configure as credenciais de acesso
Crie uma AccessKey para sua conta Alibaba Cloud ou usuário RAM e configure-a como variável de ambiente para evitar codificar as credenciais diretamente no código.
Reinicie sua IDE, terminal, outros aplicativos de desktop e serviços em segundo plano após a configuração para carregar as variáveis de ambiente atualizadas. Para obter mais informações sobre outros tipos de credenciais de acesso, consulte Configurar credenciais de acesso .
Linux
-
Anexe as variáveis de ambiente ao arquivo
~/.bashrc:echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc -
Aplique as alterações:
source ~/.bashrc -
Verifique as variáveis de ambiente:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
macOS
-
Verifique seu shell padrão:
echo $SHELL -
Configure conforme o tipo de shell utilizado:
Zsh
-
Anexe as variáveis de ambiente ao arquivo
~/.zshrc:echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Aplique as alterações:
source ~/.zshrc -
Verifique as variáveis de ambiente:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
Bash
-
Anexe as variáveis de ambiente ao arquivo
~/.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 -
Aplique as alterações:
source ~/.bash_profile -
Verifique as variáveis de ambiente:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
-
Windows
CMD
-
Defina as variáveis de ambiente no CMD:
setx TABLESTORE_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Reinicie o CMD e verifique:
echo %TABLESTORE_ACCESS_KEY_ID% echo %TABLESTORE_ACCESS_KEY_SECRET%
PowerShell
-
Execute no 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) -
Verifique as variáveis de ambiente:
[Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Inicialize o cliente
Inicialize um cliente síncrono com assinatura V4 e verifique a conexão listando as tabelas de dados.
O cliente é thread-safe e gerencia automaticamente pools de threads internos e recursos de conexão. Compartilhe uma única instância entre threads em vez de criar uma nova para cada thread ou requisição.
O acesso pela rede pública vem desativado por padrão em novas instâncias. Para acessar uma instância pela Internet, ative essa opção na página Network Management.
Modelo de coluna larga
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 séries temporais
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();
}
}
}
}
Configuração do cliente
O Tablestore SDK for Java suporta clientes síncronos e assíncronos. O cliente assíncrono oferece maior throughput para cargas de trabalho concorrentes.
Cliente assíncrono
Este cliente utiliza callbacks para processar resultados sem bloquear threads.
Modelo de coluna larga
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 séries temporais
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();
}
}
}
}
Versão da assinatura
Disponíveis desde o SDK 5.16.1, as assinaturas V4 utilizam algoritmos de criptografia e mecanismos de assinatura mais robustos para maior segurança. Sempre que possível, faça upgrade para V4. O código abaixo demonstra a inicialização com assinatura V2.
Modelo de coluna larga
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();
}
}
}
}
Assí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 séries temporais
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();
}
}
}
}
Assí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();
}
}
}
}
Compatibilidade de versões
A versão mais recente é a 5.x.x. Compatibilidade com versões anteriores:
A série de SDKs 4.x.x é compatível.
Tablestore SDK for Java V2.x.x: incompatível.
Perguntas frequentes
Como resolver conflitos de dependência da biblioteca PB ao usar o SDK?
Caso ocorra o erro java.lang.ExceptionInInitializerError, provavelmente há um conflito de dependência da biblioteca Protocol Buffers (PB) no seu projeto. Resolva o problema seguindo as instruções em Conflitos de biblioteca PB ao usar o SDK para Java.
Como proceder se ocorrer uma exceção "Signature mismatch" ao usar o SDK?
A seguinte exceção é exibida:
Error Code: OTSAuthFailed, Message: Signature mismatch., RequestId: 0005f55a-xxxx-xxxx-xxxx-xxxxxxxxxxxx, TraceId: 10b0f0e0-xxxx-xxxx-xxxx-xxxxxxxxxxxx, HttpStatus: 403
Causa: A AccessKey ID ou o AccessKey secret está incorreto.
Solução: Forneça a AccessKey ID e o AccessKey secret corretos.
O que fazer se ocorrer a exceção "Request denied by instance ACL policies" ao usar o SDK?
O SDK pode retornar o erro 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: O tipo de rede do cliente não corresponde à política de acesso da instância. Por exemplo, a instância não permite acesso pela Internet.
-
Solução: O acesso pela rede pública vem desativado por padrão. Para ativá-lo:
No console do Tablestore, clique na instância desejada.
Clique em Network Management. Em Allowed Network Type, selecione Internet e clique em Settings.
Como resolver a exceção "Request denied because this instance can only be accessed from the binded VPC" ao usar o SDK?
O SDK pode retornar o erro 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: O tipo de acesso da instância está definido como Bound VPCs Only ou Tablestore Console or Bound VPCs, mas o cliente não está em uma VPC anexada ou não está acessando o Tablestore por meio de um endpoint de VPC.
-
Solução: Permita o acesso pela Internet ou anexe uma VPC e conecte o cliente a partir dela:
No console do Tablestore, clique na instância desejada.
Clique em . Selecione um VPC ID e um VSwitch, insira um VPC Name e clique em OK.
O que fazer se ocorrer uma SocketTimeoutException ao usar o SDK?
Tempos limite no cliente podem resultar de falhas de rede, instabilidade, alta carga no servidor ou GC completo. Verifique a conectividade de rede, a latência do servidor e a atividade de GC. Consulte O que fazer se ocorrer uma SocketTimeoutException ao usar o SDK para Java para acessar o Tablestore?.
Como proceder se ocorrer a exceção "The access key id is invalid" ao usar o SDK?
A seguinte exceção ocorre durante o uso do SDK:
java.lang.IllegalArgumentException: The access key id is invalid:xxx.
Causa: A AccessKey (que inclui a AccessKey ID e o AccessKey secret) está incorreta ou contém caracteres inválidos.
Solução: Forneça as informações corretas da AccessKey.
Como resolver a exceção "java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED" ao usar o SDK?
A seguinte exceção ocorre durante o uso do SDK:
java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED
Causa: O método
shutDownjá foi chamado, encerrando os reatores de E/S do cliente.Solução: Após chamar
shutDown, reinicialize o cliente. Um cliente submetido ashutDownnão consegue atender novas requisições.