O Resource Access Management (RAM) ajuda a gerenciar identidades de usuários e permissões de acesso a recursos. Para maior segurança, utilize o par de AccessKey de um usuário do RAM para acessar recursos do Tablestore em vez das credenciais da sua conta Alibaba Cloud. Este tópico descreve como usar o par de AccessKey de um usuário do RAM para acessar recursos do Tablestore.
Contexto
Um RAM user é um tipo de identidade no Resource Access Management (RAM). Crie usuários do RAM na sua conta Alibaba Cloud e conceda permissões específicas a eles. Isso permite que diferentes usuários do RAM tenham níveis distintos de acesso aos seus recursos.
Procedimento
Para acessar o Tablestore com o par de AccessKey de um usuário do RAM, crie um usuário do RAM, conceda permissões de acesso ao Tablestore e use as credenciais desse usuário para acessar os recursos do Tablestore.
Etapa 1: Criar um usuário do RAM
Faça login no console do RAM com sua conta Alibaba Cloud ou um usuário do RAM com permissões administrativas.
No painel de navegação à esquerda, escolha Identities > Users.
Na página Users, clique em Create User.
-
Na página Create User, na seção User Account Information, configure as informações básicas do usuário:
Logon Name: O nome de login pode conter letras, dígitos, pontos (.), hifens (-) e sublinhados (_), com limite de 64 caracteres.
Display Name: O nome de exibição aceita até 128 caracteres.
Tag: Clique no ícone
e insira uma chave e um valor de tag. Tags facilitam a localização e o gerenciamento do usuário do RAM.
NotaClique em Add User para criar vários usuários do RAM em lote.
-
Na seção Access Mode, selecione Programmatic Access e clique em OK.
NotaPara permitir que o usuário do RAM faça login no Console de Gerenciamento da Alibaba Cloud, selecione Console Access.
-
Na coluna Actions, clique em Copy para salvar as informações do usuário do RAM. Também é possível copiar o AccessKey ID e o AccessKey secret individualmente.
ImportanteO AccessKey secret é exibido apenas uma vez no momento da criação e não pode ser recuperado posteriormente. Armazene-o imediatamente em um local seguro.
Etapa 2: Conceder permissões ao usuário do RAM para o Tablestore
Após criar um usuário do RAM, conceda permissões de acesso ao Tablestore.
Política padrão
Este exemplo mostra como conceder permissões de acesso ao Tablestore anexando a política AliyunOTSFullAccess a um usuário do RAM.
A política AliyunOTSFullAccess concede acesso total ao Tablestore. Outras políticas padrão também podem ser usadas:
Para acesso somente leitura, conceda a política
AliyunOTSReadOnlyAccess.Para acesso somente gravação, conceda a política
AliyunOTSWriteOnlyAccess.
No painel de navegação à esquerda, escolha Identities > Users.
Na página Users, localize o usuário do RAM desejado.
Clique em Add Permissions na coluna Actions correspondente ao usuário do RAM.
No painel Grant Permission, na seção Policy, pesquise e selecione
AliyunOTSFullAccess.Clique em Grant Permissions.
Política personalizada
-
Crie uma política personalizada.
No painel de navegação à esquerda, escolha Permissions > Policies.
Na página Policies, clique em Create Policy.
-
Na página Create Policy, clique na aba JSON, insira o script da política no editor e clique em OK.
NotaO script de exemplo a seguir concede permissão de acesso a uma única instância. Personalize a política para controlar o acesso no nível de tabela, operação de API ou com base em condições como endereço IP ou horário de acesso. Para obter mais informações sobre políticas do RAM, consulte Custom RAM policy.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "ots:*", "Resource": "acs:ots:*:*:instance/your_instance_name*" } ] } Na caixa de diálogo Create Policy, insira um nome para a política, como
TestRAMPolicy, e clique em OK.
-
Anexe a política personalizada ao usuário do RAM.
No painel de navegação à esquerda, escolha Identities > Users.
Na página Users, localize o usuário do RAM desejado.
Clique em Add Permissions na coluna Actions correspondente ao usuário do RAM.
No painel Grant Permission, na seção Policy, pesquise e selecione a política personalizada criada.
Clique em Grant Permissions.
Na página Users, clique no nome de usuário para acessar a página de detalhes. Na aba Permissions, visualize as políticas concedidas.
Etapa 3: Usar o par de AccessKey para acessar o Tablestore
Antes de começar
Crie uma instância e uma tabela de dados no console do Tablestore.
-
Obtenha o nome da instância, o endpoint e o region ID.
ImportantePor padrão, o acesso pela rede pública fica desativado em instâncias recém-criadas. Se precisar acessar recursos em uma instância pela internet, ative o acesso à rede pública para a instância.
-
Configure as variáveis de ambiente. Após concluir a configuração, reinicie ou atualize seu ambiente de compilação e execução, incluindo IDE, interface de linha de comando, outros aplicativos de desktop e serviços em segundo plano, para garantir o carregamento correto das variáveis de ambiente mais recentes do sistema.
Linux
-
Execute os comandos a seguir na interface de linha de comando para adicionar as configurações de 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 -
Execute o comando a seguir para aplicar as alterações:
source ~/.bashrc -
Verifique se as variáveis de ambiente entraram em vigor com os comandos abaixo:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
macOS
-
Execute o comando a seguir no terminal para verificar o tipo de Shell padrão.
echo $SHELL -
Realize as operações de acordo com o tipo de Shell padrão.
Zsh
-
Execute os comandos a seguir para adicionar as configurações de 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 -
Execute o comando a seguir para aplicar as alterações:
source ~/.zshrc -
Verifique se as variáveis de ambiente entraram em vigor com os comandos abaixo:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
Bash
-
Execute os comandos a seguir para adicionar as configurações de 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 -
Execute o comando a seguir para aplicar as alterações:
source ~/.bash_profile -
Verifique se as variáveis de ambiente entraram em vigor com os comandos abaixo:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
-
Windows
CMD
-
Execute os comandos a seguir no CMD para definir as variáveis de ambiente.
setx TABLESTORE_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Após reiniciar o CMD, verifique se as variáveis de ambiente entraram em vigor com os comandos abaixo:
echo %TABLESTORE_ACCESS_KEY_ID% echo %TABLESTORE_ACCESS_KEY_SECRET%
PowerShell
-
Execute o comando a seguir 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 se as variáveis de ambiente entraram em vigor com os comandos abaixo:
[Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
Instale o SDK do Tablestore para a linguagem de programação de sua preferência.
Java
Em projetos Maven, adicione a seguinte dependência ao arquivo pom.xml:
<dependency> <groupId>com.aliyun.openservices</groupId> <artifactId>tablestore</artifactId> <version>5.17.4</version> </dependency>
Para obter mais informações, consulte Install Tablestore SDK for Java.
Go
Execute o comando
go mod init <DIRNAME>no diretório do projeto para gerar o arquivo go.mod. Em seguida, execute o comando a seguir para instalar o SDK do Tablestore para Go:Nota<DIRNAME>indica o caminho do diretório do projeto. Substitua <DIRNAME> pelo caminho real do diretório do seu projeto.go get github.com/aliyun/aliyun-tablestore-go-sdk/tablestorePara obter mais informações, consulte Install Tablestore SDK for Go.
Python
Use o pip para instalar o SDK do Tablestore para Python com o comando a seguir:
sudo pip install tablestorePara obter mais informações, consulte Install Tablestore SDK for Python.
Node.js
Instale o SDK do Tablestore para Node.js com o comando a seguir:
npm install tablestorePara obter mais informações, consulte Install Tablestore SDK for Node.js.
.NET
Para obter mais informações, consulte Install Tablestore .NET SDK.
PHP
Para obter mais informações, consulte Install Tablestore PHP SDK.
Modelo de coluna larga
Para usar o modelo de coluna larga, inicialize o cliente com o par de AccessKey do usuário do RAM.
Java
Assinatura V4
O código de exemplo Java a seguir usa uma assinatura V4 para inicializar um cliente e recuperar os nomes de todas as tabelas de dados em uma instância.
import com.alicloud.openservices.tablestore.ClientConfiguration;
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.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.ListTableResponse;
public class InitClientV4 {
public static void main(String[] args) {
// Replace yourRegion with the region where your instance is located, for example, cn-hangzhou.
final String region = "yourRegion";
// Replace yourInstanceName with the name of your instance.
final String instanceName = "yourInstanceName";
// Replace yourEndpoint with the endpoint of your instance.
final String endpoint = "yourEndpoint";
// Obtain the AccessKey ID and AccessKey secret from environment variables.
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// Construct a V4 signature.
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);
// Initialize the Tablestore client.
SyncClient client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// You can specify a ClientConfiguration to modify the default settings. The following example shows some custom settings.
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Set the connection timeout period in milliseconds.
clientConfiguration.setSocketTimeoutInMillisecond(5000); // Set the socket timeout period in milliseconds.
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Set a retry policy. If a retry policy is not set, the default retry policy is used.
SyncClient client = new SyncClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// List the data tables in the instance and print their names to the console.
ListTableResponse listTableResponse = client.listTable();
listTableResponse.getTableNames().forEach(System.out::println);
// Shut down the Tablestore client.
client.shutdown();
}
}
Assinatura V2
O código de exemplo Java a seguir usa uma assinatura V2 para inicializar um cliente e recuperar os nomes de todas as tabelas de dados em uma instância.
import com.alicloud.openservices.tablestore.ClientConfiguration;
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.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.ListTableResponse;
public class InitClientV2 {
public static void main(String[] args) {
// Replace yourInstanceName with the name of your instance.
final String instanceName = "yourInstanceName";
// Replace yourEndpoint with the endpoint of your instance.
final String endpoint = "yourEndpoint";
// Obtain the AccessKey ID and AccessKey secret from environment variables.
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// Construct a V2 signature.
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
CredentialsProvider provider = new DefaultCredentialProvider(credentials);
// Initialize the Tablestore client.
SyncClient client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// You can specify a ClientConfiguration to modify the default settings. The following example shows some custom settings.
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Set the connection timeout period in milliseconds.
clientConfiguration.setSocketTimeoutInMillisecond(5000); // Set the socket timeout period in milliseconds.
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Set a retry policy. If a retry policy is not set, the default retry policy is used.
SyncClient client = new SyncClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// List the data tables in the instance and print their names to the console.
ListTableResponse listTableResponse = client.listTable();
listTableResponse.getTableNames().forEach(System.out::println);
// Shut down the Tablestore client.
client.shutdown();
}
}
Go
O código de exemplo Go a seguir inicializa um cliente e recupera os nomes de todas as tabelas de dados em uma instância.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)
func main() {
// Replace yourInstanceName with the name of your instance.
instanceName := "yourInstanceName"
// Replace yourEndpoint with the endpoint of your instance.
endpoint := "yourEndpoint"
// Obtain the AccessKey ID and AccessKey secret from environment variables.
accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
// Initialize the Tablestore client.
client := tablestore.NewClient(endpoint, instanceName, accessKeyId, accessKeySecret)
// List the data tables in the instance and print their names to the console.
tables, err := client.ListTable()
if err != nil {
fmt.Println("Failed to list table")
} else {
for _, table := range (tables.TableNames) {
fmt.Println(table)
}
}
}
Python
O código de exemplo Python a seguir inicializa um cliente e recupera os nomes de todas as tabelas de dados em uma instância.
# -*- coding: utf-8 -*-
import os
from tablestore import OTSClient
# Replace yourInstanceName with the name of your instance.
instance_name = "yourInstanceName"
# Replace yourEndpoint with the endpoint of your instance.
endpoint = "yourEndpoint"
# Obtain the AccessKey ID and AccessKey secret from environment variables.
access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID")
access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")
# Initialize the Tablestore client.
client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name)
# List the data tables in the instance and print their names to the console.
resp = client.list_table()
for table_name in resp:
print(table_name)
Node.js
O código de exemplo Node.js a seguir inicializa um cliente e recupera os nomes de todas as tabelas de dados em uma instância.
// This is a relative path. Adjust it based on your actual file structure.
var TableStore = require('../index.js');
// Replace yourInstanceName with the name of your instance.
var instancename = 'yourInstanceName';
// Replace yourEndpoint with the endpoint of your instance.
var endpoint = 'yourEndpoint';
// Obtain the AccessKey ID and AccessKey secret from environment variables.
var accessKeyId = process.env.TABLESTORE_ACCESS_KEY_ID;
var secretAccessKey = process.env.TABLESTORE_ACCESS_KEY_SECRET;
// Initialize the Tablestore client.
var client = new TableStore.Client({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
endpoint: endpoint,
instancename: instancename
});
// List the data tables in the instance and print their names to the console.
client.listTable({}, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
console.log('success:', data);
});
.NET
O código de exemplo .NET a seguir inicializa um cliente e recupera os nomes de todas as tabelas de dados em uma instância.
using Aliyun.OTS.Request;
using Aliyun.OTS.Response;
using System;
namespace Aliyun.OTS.Samples
{
public class Sample
{
public static void InitializeClient()
{
// Replace yourEndpoint with the endpoint of your instance.
string endpoint = "yourEndpoint";
// Replace yourInstanceName with the name of your instance.
string instanceName = "yourInstanceName";
// Obtain the AccessKey ID and AccessKey secret from environment variables.
string accessKeyId = Environment.GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID");
string accessKeySecret = Environment.GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET");
OTSClientConfig config = new OTSClientConfig(endpoint, accessKeyId, accessKeySecret, instanceName)
{
OTSDebugLogHandler = null,
OTSErrorLogHandler = null
};
try
{
// Initialize the Tablestore client.
OTSClient client = new OTSClient(config);
// List the data tables in the instance and print their names.
ListTableResponse response = client.ListTable(new ListTableRequest());
foreach (var tableName in response.TableNames)
{
Console.WriteLine(tableName);
}
}
catch (Exception ex)
{
Console.WriteLine("List table failed, exception:{0}", ex.Message);
}
}
}
}
PHP
O código de exemplo PHP a seguir inicializa um cliente e recupera os nomes de todas as tabelas de dados em uma instância.
<?php
// This is a relative path. Adjust it based on your actual file structure.
require (__DIR__ . '/../../vendor/autoload.php');
use Aliyun\OTS\OTSClient as OTSClient;
// Replace yourInstanceName with the name of your instance.
$instanceName = "yourInstanceName";
// Replace yourEndpoint with the endpoint of your instance.
$endpoint = "yourEndpoint";
// Obtain the AccessKey ID and AccessKey secret from system environment variables.
$accessKeyId = getenv('TABLESTORE_ACCESS_KEY_ID');
$accessKeySecret = getenv('TABLESTORE_ACCESS_KEY_SECRET');
// Initialize the Tablestore client.
$client = new OTSClient(array(
'EndPoint' => $endpoint,
'AccessKeyID' => $accessKeyId,
'AccessKeySecret' => $accessKeySecret,
'InstanceName' => $instanceName,
));
// List the data tables in the instance and print their names to the console.
$response = $client->listTable (array ());
print json_encode ($response);
Modelo de séries temporais
Para usar o modelo de séries temporais, inicialize o cliente com o par de AccessKey do usuário do RAM. Atualmente, os SDKs para Java, Go e Python oferecem suporte a esse modelo.
Java
Assinatura V4
O código de exemplo Java a seguir usa uma assinatura V4 para inicializar um cliente e recuperar os nomes de todas as tabelas de séries temporais em uma instância.
import com.alicloud.openservices.tablestore.ClientConfiguration;
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.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;
public class InitTimeseriesClientV4 {
public static void main(String[] args) {
// Replace yourRegion with the region where your instance is located, for example, cn-hangzhou.
final String region = "yourRegion";
// Replace yourInstanceName with the name of your instance.
final String instanceName = "yourInstanceName";
// Replace yourEndpoint with the endpoint of your instance.
final String endpoint = "yourEndpoint";
// Obtain the AccessKey ID and AccessKey secret from environment variables.
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// Construct a V4 signature.
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);
// Initialize the Tablestore client.
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// You can specify a ClientConfiguration to modify the default settings. The following example shows some custom settings.
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Set the connection timeout period in milliseconds.
clientConfiguration.setSocketTimeoutInMillisecond(5000); // Set the socket timeout period in milliseconds.
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Set a retry policy. If a retry policy is not set, the default retry policy is used.
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// List the time series tables in the instance and print their names to the console.
ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();
listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
// Shut down the Tablestore client.
client.shutdown();
}
}
Assinatura V2
O código de exemplo Java a seguir usa uma assinatura V2 para inicializar um cliente e recuperar os nomes de todas as tabelas de séries temporais em uma instância.
import com.alicloud.openservices.tablestore.ClientConfiguration;
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.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;
public class InitTimeseriesClientV2 {
public static void main(String[] args) {
// Replace yourInstanceName with the name of your instance.
final String instanceName = "yourInstanceName";
// Replace yourEndpoint with the endpoint of your instance.
final String endpoint = "yourEndpoint";
// Obtain the AccessKey ID and AccessKey secret from environment variables.
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// Construct a V2 signature.
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
CredentialsProvider provider = new DefaultCredentialProvider(credentials);
// Initialize the Tablestore client.
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// You can specify a ClientConfiguration to modify the default settings. The following example shows some custom settings.
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Set the connection timeout period in milliseconds.
clientConfiguration.setSocketTimeoutInMillisecond(5000); // Set the socket timeout period in milliseconds.
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Set a retry policy. If a retry policy is not set, the default retry policy is used.
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// List the time series tables in the instance and print their names to the console.
ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();
listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
// Shut down the Tablestore client.
client.shutdown();
}
}
Go
O código de exemplo Go a seguir inicializa um cliente e recupera os nomes de todas as tabelas de séries temporais em uma instância.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)
func main() {
// Replace yourInstanceName with the name of your instance.
instanceName := "yourInstanceName"
// Replace yourEndpoint with the endpoint of your instance.
endpoint := "yourEndpoint"
// Obtain the AccessKey ID and AccessKey secret from environment variables.
accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
// Initialize the Tablestore client.
client := tablestore.NewTimeseriesClient(endpoint, instanceName, accessKeyId, accessKeySecret)
// List the time series tables in the instance and print their names to the console.
timeseriesTables, err := client.ListTimeseriesTable()
if err != nil {
fmt.Println("Failed to list table")
} else {
for _, timeseriesTablesMeta := range (timeseriesTables.GetTimeseriesTableMeta()) {
fmt.Println(timeseriesTablesMeta.GetTimeseriesTableName())
}
}
}
Python
O código de exemplo Python a seguir inicializa um cliente e recupera os nomes de todas as tabelas de séries temporais em uma instância.
# -*- coding: utf-8 -*-
import os
from tablestore import OTSClient
# Replace yourInstanceName with the name of your instance.
instance_name = "yourInstanceName"
# Replace yourEndpoint with the endpoint of your instance.
endpoint = "yourEndpoint"
# Obtain the AccessKey ID and AccessKey secret from environment variables.
access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID")
access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")
# Initialize the Tablestore client.
client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name)
# List the time series tables in the instance and print their names to the console.
response = client.list_timeseries_table()
for tableMeta in response:
print(tableMeta.timeseries_table_name)