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 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 RAM para acessar recursos do Tablestore.
Contexto
Um usuário RAM é um tipo de identidade no Resource Access Management (RAM). Crie usuários RAM na sua conta Alibaba Cloud e conceda permissões específicas a eles. Isso permite que diferentes usuários RAM tenham níveis distintos de acesso aos seus recursos.
Procedimento
Para acessar o Tablestore com o par de AccessKey de um usuário RAM, crie um usuário RAM, conceda permissões de acesso ao Tablestore e use o Tablestore desse usuário para acessar os recursos do Tablestore.
Etapa 1: Criar um usuário RAM
Faça login no console RAM com sua conta Alibaba Cloud ou um usuário 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 (.), hífens (-) e sublinhados (_), com limite de 64 caracteres.
Display Name: O nome de exibição pode ter até 128 caracteres.
Tag: Clique no ícone
e insira uma chave e um valor de tag. Adicionar tags facilita a localização e o gerenciamento do usuário RAM.
NotaClique em Add User para criar vários usuários RAM em lote.
-
Na seção Access Mode, selecione Programmatic Access e clique em OK.
NotaPara permitir que o usuário 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 RAM. Também é possível copiar o AccessKey ID e o AccessKey secret individualmente.
ImportanteO AccessKey secret aparece 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 RAM para o Tablestore
Após criar um usuário RAM, conceda permissões para acessar o 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 RAM.
A política AliyunOTSFullAccess concede acesso total ao Tablestore. Também é possível conceder permissões usando outras políticas padrão:
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 RAM desejado.
Clique em Add Permissions na coluna Actions correspondente ao usuário 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 para acessar uma única instância. Personalize a política para controlar o acesso no nível de tabela ou operação de API, ou com base em condições como endereço IP ou horário de acesso. Para mais informações sobre políticas RAM, consulte Política RAM personalizada.
{ "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 RAM.
No painel de navegação à esquerda, escolha Identities > Users.
Na página Users, localize o usuário RAM desejado.
Clique em Add Permissions na coluna Actions correspondente ao usuário 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 um usuário para acessar a página de detalhes. Na aba Permissions, visualize as políticas concedidas ao usuário.
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 ID da região.
ImportantePor padrão, o acesso pela rede pública fica desativado em instâncias recém-criadas. Caso precise acessar recursos de uma instância pela internet, ative o acesso pela 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 que as variáveis de ambiente mais recentes do sistema sejam carregadas corretamente.
Linux
-
Execute os comandos abaixo 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 -
Execute os comandos abaixo para verificar se as variáveis de ambiente foram aplicadas corretamente:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
macOS
-
Execute o comando abaixo no terminal para verificar o tipo de Shell padrão.
echo $SHELL -
Realize as operações conforme o tipo de Shell padrão.
Zsh
-
Execute os comandos abaixo 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 -
Execute os comandos abaixo para verificar se as variáveis de ambiente foram aplicadas corretamente:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
Bash
-
Execute os comandos abaixo 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 -
Execute os comandos abaixo para verificar se as variáveis de ambiente foram aplicadas corretamente:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
-
Windows
CMD
-
Execute os comandos abaixo 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, execute os comandos abaixo para verificar se as variáveis de ambiente foram aplicadas corretamente:
echo %TABLESTORE_ACCESS_KEY_ID% echo %TABLESTORE_ACCESS_KEY_SECRET%
PowerShell
-
Execute o comando abaixo 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) -
Execute os comandos abaixo para verificar se as variáveis de ambiente foram aplicadas corretamente:
[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
Se você utiliza 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.4</version> </dependency>
Para mais informações, consulte Instalar o SDK do Tablestore para 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 abaixo 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 mais informações, consulte Instalar o SDK do Tablestore para Go.
Python
Execute o comando abaixo para usar o pip e instalar o SDK do Tablestore para Python:
sudo pip install tablestorePara mais informações, consulte Instalar o SDK do Tablestore para Python.
Node.js
Execute o comando abaixo para instalar o SDK do Tablestore para Node.js:
npm install tablestorePara mais informações, consulte Instalar o SDK do Tablestore para Node.js.
.NET
Para mais informações, consulte Instalar o SDK do Tablestore para .NET.
PHP
Para mais informações, consulte Instalar o SDK do Tablestore para PHP.
Modelo de coluna larga
Para utilizar o modelo de coluna larga, inicialize o cliente com o par de AccessKey do usuário RAM.
Java
Assinatura V4
O código de exemplo Java a seguir demonstra como usar 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 demonstra como usar 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 demonstra como inicializar um cliente e recuperar 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 demonstra como inicializar um cliente e recuperar 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 demonstra como inicializar um cliente e recuperar 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 demonstra como inicializar um cliente e recuperar 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 demonstra como inicializar um cliente e recuperar 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érie temporal
Para utilizar o modelo de série temporal, inicialize o cliente com o par de AccessKey do usuário RAM. Atualmente, os SDKs para Java, Go e Python oferecem suporte ao modelo de série temporal.
Java
Assinatura V4
O código de exemplo Java a seguir demonstra como usar uma assinatura V4 para inicializar um cliente e recuperar os nomes de todas as tabelas de série temporal 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 demonstra como usar uma assinatura V2 para inicializar um cliente e recuperar os nomes de todas as tabelas de série temporal 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 demonstra como inicializar um cliente e recuperar os nomes de todas as tabelas de série temporal 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 demonstra como inicializar um cliente e recuperar os nomes de todas as tabelas de série temporal 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)