Resource Access Management (RAM) le permite gestionar identidades de usuarios y permisos de acceso a recursos. Para mejorar la seguridad, se recomienda utilizar el par de AccessKey de un usuario de RAM para acceder a los recursos de Tablestore en lugar de usar las credenciales de su cuenta de Alibaba Cloud. Este tema describe cómo usar el par de AccessKey de un usuario de RAM para acceder a los recursos de Tablestore.
Contexto
Un RAM user es un tipo de identidad en Resource Access Management (RAM). Puede crear usuarios de RAM bajo su cuenta de Alibaba Cloud y otorgarles permisos específicos. Esto permite que distintos usuarios de RAM tengan diferentes niveles de acceso a sus recursos.
Procedimiento
Para acceder a Tablestore con el par de AccessKey de un usuario de RAM, cree un usuario de RAM, otórguele permisos para acceder a Tablestore y luego utilice dicho usuario de Tablestore para acceder a los recursos de Tablestore.
Paso 1: Crear un usuario de RAM
Inicie sesión en la consola de RAM con su cuenta de Alibaba Cloud o con un usuario de RAM que tenga permisos administrativos.
En el panel de navegación izquierdo, seleccione Identities > Users.
En la página Users, haga clic en Create User.
-
En la página Create User, dentro de la sección User Account Information, configure la información básica del usuario:
Logon Name: El nombre de inicio de sesión puede contener letras, dígitos, puntos (.), guiones (-) y guiones bajos (_). Su longitud máxima es de 64 caracteres.
Display Name: El nombre para mostrar puede tener una longitud máxima de 128 caracteres.
Tag: Haga clic en el icono
e introduzca una clave de etiqueta y un valor de etiqueta. Agregar una etiqueta facilita la búsqueda y gestión del usuario de RAM.
NotaPuede hacer clic en Add User para crear varios usuarios de RAM en lote.
-
En la sección Access Mode, seleccione Programmatic Access y luego haga clic en OK.
NotaPara permitir que el usuario de RAM inicie sesión en la consola de administración de Alibaba Cloud, seleccione Console Access.
-
En la columna Actions, haga clic en Copy para guardar la información del usuario de RAM. También puede copiar el AccessKey ID y el AccessKey secret por separado.
ImportanteEl AccessKey secret se muestra únicamente una vez al momento de la creación y no se puede recuperar posteriormente. Guárdelo de inmediato en un lugar seguro.
Paso 2: Otorgar permisos de Tablestore al usuario de RAM
Después de crear un usuario de RAM, debe otorgarle permisos para acceder a Tablestore.
Directiva predeterminada
Este ejemplo muestra cómo otorgar permisos a un usuario de RAM para acceder a Tablestore mediante la vinculación de la directiva AliyunOTSFullAccess.
La directiva AliyunOTSFullAccess otorga acceso total a Tablestore. También puede otorgar permisos mediante otras directivas predeterminadas:
Para acceso de solo lectura, otorgue al usuario de RAM la directiva
AliyunOTSReadOnlyAccess.Para acceso de solo escritura, otorgue al usuario de RAM la directiva
AliyunOTSWriteOnlyAccess.
En el panel de navegación izquierdo, seleccione Identities > Users.
En la página Users, localice al usuario de RAM deseado.
Haga clic en Add Permissions en la columna Actions correspondiente al usuario de RAM.
En el panel Grant Permission, dentro de la sección Policy, busque y seleccione
AliyunOTSFullAccess.Haga clic en Grant Permissions.
Directiva personalizada
-
Cree una directiva personalizada.
En el panel de navegación izquierdo, seleccione Permissions > Policies.
En la página Policies, haga clic en Create Policy.
-
En la página Create Policy, haga clic en la pestaña JSON, introduzca el script de su directiva en el editor y luego haga clic en OK.
NotaEl siguiente script de ejemplo otorga a un usuario de RAM permiso para acceder a una sola instancia. Puede personalizar la directiva para controlar el acceso a nivel de tabla u operación de API, o bien basarse en condiciones como la dirección IP o la hora de acceso. Para obtener más información sobre las directivas de RAM, consulte Custom RAM policy.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "ots:*", "Resource": "acs:ots:*:*:instance/your_instance_name*" } ] } En el cuadro de diálogo Create Policy, introduzca un nombre de directiva, por ejemplo
TestRAMPolicy, y luego haga clic en OK.
-
Vincule la directiva personalizada al usuario de RAM.
En el panel de navegación izquierdo, seleccione Identities > Users.
En la página Users, localice al usuario de RAM deseado.
Haga clic en Add Permissions en la columna Actions correspondiente al usuario de RAM.
En el panel Grant Permission, dentro de la sección Policy, busque y seleccione la directiva personalizada que creó.
Haga clic en Grant Permissions.
En la página Users, puede hacer clic en un nombre de usuario para ir a la página de detalles del usuario. En la pestaña Permissions, podrá consultar las directivas otorgadas al usuario.
Paso 3: Usar el par de AccessKey para acceder a Tablestore
Antes de empezar
Cree una instancia y una tabla de datos en la consola de Tablestore.
-
Obtenga el nombre de la instancia, endpoint y region ID.
ImportanteDe forma predeterminada, el acceso por red pública está deshabilitado en las instancias recién creadas. Si necesita acceder a los recursos de una instancia a través de Internet, debe enable public network access for the instance.
-
Configure las variables de entorno. Una vez completada la configuración, reinicie o actualice su entorno de compilación y ejecución, incluyendo IDE, interfaz de línea de comandos, otras aplicaciones de escritorio y servicios en segundo plano, para asegurar que las variables de entorno del sistema más recientes se carguen correctamente.
Linux
-
Ejecute los siguientes comandos en la interfaz de línea de comandos para agregar la configuración de variables de entorno al archivo
~/.bashrc.echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc -
Ejecute el siguiente comando para aplicar los cambios:
source ~/.bashrc -
Ejecute los siguientes comandos para comprobar si las variables de entorno surten efecto:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
macOS
-
Ejecute el siguiente comando en la terminal para verificar el tipo de shell predeterminado.
echo $SHELL -
Realice las operaciones correspondientes según el tipo de shell predeterminado.
Zsh
-
Ejecute los siguientes comandos para agregar la configuración de variables de entorno al archivo
~/.zshrc.echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Ejecute el siguiente comando para aplicar los cambios:
source ~/.zshrc -
Ejecute los siguientes comandos para comprobar si las variables de entorno surten efecto:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
Bash
-
Ejecute los siguientes comandos para agregar la configuración de variables de entorno al archivo
~/.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 -
Ejecute el siguiente comando para aplicar los cambios:
source ~/.bash_profile -
Ejecute los siguientes comandos para comprobar si las variables de entorno surten efecto:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
-
Windows
CMD
-
Ejecute los siguientes comandos en CMD para establecer las variables de entorno.
setx TABLESTORE_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Después de reiniciar CMD, ejecute los siguientes comandos para comprobar si las variables de entorno surten efecto:
echo %TABLESTORE_ACCESS_KEY_ID% echo %TABLESTORE_ACCESS_KEY_SECRET%
PowerShell
-
Ejecute el siguiente comando en PowerShell:
[Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) -
Ejecute los siguientes comandos para comprobar si las variables de entorno surten efecto:
[Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
Instale el SDK de Tablestore correspondiente a su lenguaje de programación preferido.
Java
Si utiliza un proyecto Maven, agregue la siguiente dependencia a su archivo pom.xml:
<dependency> <groupId>com.aliyun.openservices</groupId> <artifactId>tablestore</artifactId> <version>5.17.4</version> </dependency>
Para obtener más información, consulte Install Tablestore SDK for Java.
Go
Ejecute el comando
go mod init <DIRNAME>en el directorio del proyecto para generar el archivo go.mod. A continuación, ejecute el siguiente comando para instalar el SDK de Tablestore para Go:Nota<DIRNAME>indica la ruta del directorio del proyecto. Reemplace <DIRNAME> con la ruta real del directorio de su proyecto.go get github.com/aliyun/aliyun-tablestore-go-sdk/tablestorePara obtener más información, consulte Install Tablestore SDK for Go.
Python
Ejecute el siguiente comando para usar pip e instalar el SDK de Tablestore para Python:
sudo pip install tablestorePara obtener más información, consulte Install Tablestore SDK for Python.
Node.js
Ejecute el siguiente comando para instalar el SDK de Tablestore para Node.js:
npm install tablestorePara obtener más información, consulte Install Tablestore SDK for Node.js.
.NET
Para obtener más información, consulte Install Tablestore .NET SDK.
PHP
Para obtener más información, consulte Install Tablestore PHP SDK.
Modelo de columnas anchas
Para usar el modelo de columnas anchas, inicialice el cliente con el par de AccessKey del usuario de RAM.
Java
Firma V4
El siguiente código de ejemplo en Java muestra cómo usar una firma V4 para inicializar un cliente y obtener los nombres de todas las tablas de datos en una instancia.
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();
}
}
Firma V2
El siguiente código de ejemplo en Java muestra cómo usar una firma V2 para inicializar un cliente y obtener los nombres de todas las tablas de datos en una instancia.
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
El siguiente código de ejemplo en Go muestra cómo inicializar un cliente y obtener los nombres de todas las tablas de datos en una instancia.
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
El siguiente código de ejemplo en Python muestra cómo inicializar un cliente y obtener los nombres de todas las tablas de datos en una instancia.
# -*- 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
El siguiente código de ejemplo en Node.js muestra cómo inicializar un cliente y obtener los nombres de todas las tablas de datos en una instancia.
// 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
El siguiente código de ejemplo en .NET muestra cómo inicializar un cliente y obtener los nombres de todas las tablas de datos en una instancia.
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
El siguiente código de ejemplo en PHP muestra cómo inicializar un cliente y obtener los nombres de todas las tablas de datos en una instancia.
<?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 series temporales
Para usar el modelo de series temporales, inicialice el cliente con el par de AccessKey del usuario de RAM. Actualmente, el modelo de series temporales es compatible con los SDK para Java, Go y Python.
Java
Firma V4
El siguiente código de ejemplo en Java muestra cómo usar una firma V4 para inicializar un cliente y obtener los nombres de todas las tablas de series temporales en una instancia.
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();
}
}
Firma V2
El siguiente código de ejemplo en Java muestra cómo usar una firma V2 para inicializar un cliente y obtener los nombres de todas las tablas de series temporales en una instancia.
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
El siguiente código de ejemplo en Go muestra cómo inicializar un cliente y obtener los nombres de todas las tablas de series temporales en una instancia.
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
El siguiente código de ejemplo en Python muestra cómo inicializar un cliente y obtener los nombres de todas las tablas de series temporales en una instancia.
# -*- 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)