Todos os produtos
Search
Central de documentação

Tablestore:Access Tablestore with a RAM user's AccessKey pair

Última atualização: Jul 16, 2026

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

  1. Faça login no console RAM com sua conta Alibaba Cloud ou um usuário RAM com permissões administrativas.

  2. No painel de navegação à esquerda, escolha Identities > Users.

  3. Na página Users, clique em Create User.

  4. 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 edit e insira uma chave e um valor de tag. Adicionar tags facilita a localização e o gerenciamento do usuário RAM.

    Nota

    Clique em Add User para criar vários usuários RAM em lote.

  5. Na seção Access Mode, selecione Programmatic Access e clique em OK.

    Nota

    Para permitir que o usuário RAM faça login no Console de Gerenciamento da Alibaba Cloud, selecione Console Access.

  6. 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.

    Importante

    O 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.

Nota

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.

  1. No painel de navegação à esquerda, escolha Identities > Users.

  2. Na página Users, localize o usuário RAM desejado.

  3. Clique em Add Permissions na coluna Actions correspondente ao usuário RAM.

  4. No painel Grant Permission, na seção Policy, pesquise e selecione AliyunOTSFullAccess.

  5. Clique em Grant Permissions.

Política personalizada

  1. Crie uma política personalizada.

    1. No painel de navegação à esquerda, escolha Permissions > Policies.

    2. Na página Policies, clique em Create Policy.

    3. Na página Create Policy, clique na aba JSON, insira o script da política no editor e clique em OK.

      Nota

      O 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*"
          }
        ]
      }
    4. Na caixa de diálogo Create Policy, insira um nome para a política, como TestRAMPolicy, e clique em OK.

  2. Anexe a política personalizada ao usuário RAM.

    1. No painel de navegação à esquerda, escolha Identities > Users.

    2. Na página Users, localize o usuário RAM desejado.

    3. Clique em Add Permissions na coluna Actions correspondente ao usuário RAM.

    4. No painel Grant Permission, na seção Policy, pesquise e selecione a política personalizada criada.

    5. 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

  1. Crie uma instância e uma tabela de dados no console do Tablestore.

  2. Obtenha o nome da instância, o endpoint e o ID da região.

    Importante

    Por 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.

  3. 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

    1. 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
    2. Execute o comando a seguir para aplicar as alterações:

      source ~/.bashrc
    3. 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

    1. Execute o comando abaixo no terminal para verificar o tipo de Shell padrão.

      echo $SHELL
    2. Realize as operações conforme o tipo de Shell padrão.

      Zsh

      1. 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
      2. Execute o comando a seguir para aplicar as alterações:

        source ~/.zshrc
      3. 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

      1. 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
      2. Execute o comando a seguir para aplicar as alterações:

        source ~/.bash_profile
      3. 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

    1. 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"
    2. 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

    1. 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)
    2. 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)
  4. 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/tablestore

    Para 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 tablestore

    Para 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 tablestore

    Para 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)

Perguntas frequentes

Par de AccessKey perdido

Crie um segundo par de AccessKey para rodízio. Após confirmar que o novo par funciona corretamente, exclua o antigo. Para mais informações, consulte Realizar rodízio do par de AccessKey de um usuário RAM.

Pares de AccessKey gerenciados pelo usuário

No console RAM, acesse a página Settings. Na seção Global Security, ative a configuração Allow Users to Manage Their Access Keys. Com essa configuração ativada, os usuários RAM podem criar, desativar e excluir seus próprios pares de AccessKey. Para mais informações, consulte Gerenciar configurações de segurança para usuários RAM e Criar um par de AccessKey.

Erro de negação por política ACL

O tipo de rede utilizado pelo cliente não atende aos requisitos de acesso à rede da instância. Configure o Allowed Network Type na aba Network Management da página Instance Management no console do Tablestore. Para mais informações, consulte Erro "Request denied by instance ACL policies" ao usar um SDK para acessar o Tablestore.

No console do Tablestore, acesse a página . Na aba , configure o . Para mais informações, consulte .