Instale e configure o Tablestore SDK for Go para trabalhar com os modelos WideColumn, TimeSeries e Timeline.
Início rápido
Instale o SDK e inicialize um cliente do Tablestore.
Pré-requisitos
Go 1.4 ou posterior instalado. Baixe na página oficial de download do Go.
Uma IDE para Go, como GoLand ou Visual Studio Code com a extensão Go.
Instalar o SDK
Execute go mod init <DIRNAME> no diretório do projeto para gerar um arquivo go.mod e instale o SDK:
<DIRNAME> é o caminho do diretório do projeto.
go get github.com/aliyun/aliyun-tablestore-go-sdk/tablestore
Os programas de exemplo para cada modelo estão na pasta sample do repositório Tablestore SDK for Go.
Configurar credenciais de acesso
Crie uma AccessKey para sua conta Alibaba Cloud ou usuário RAM e configure-a como variável de ambiente para evitar codificar as credenciais diretamente no código.
Reinicie a IDE, o terminal, outros aplicativos de desktop e serviços em segundo plano após a configuração para carregar as variáveis de ambiente atualizadas. Para obter mais informações sobre outros tipos de credenciais de acesso, consulte Configurar credenciais de acesso .
Linux
-
Adicione as variáveis de ambiente ao arquivo
~/.bashrc:echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc -
Aplique as alterações:
source ~/.bashrc -
Verifique as variáveis de ambiente:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
macOS
-
Verifique o shell padrão:
echo $SHELL -
Configure conforme o tipo de shell:
Zsh
-
Adicione as variáveis de ambiente ao arquivo
~/.zshrc:echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Aplique as alterações:
source ~/.zshrc -
Verifique as variáveis de ambiente:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
Bash
-
Adicione as variáveis de ambiente ao arquivo
~/.bash_profile:echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Aplique as alterações:
source ~/.bash_profile -
Verifique as variáveis de ambiente:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
-
Windows
CMD
-
Defina as variáveis de ambiente no CMD:
setx TABLESTORE_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Reinicie o CMD e verifique:
echo %TABLESTORE_ACCESS_KEY_ID% echo %TABLESTORE_ACCESS_KEY_SECRET%
PowerShell
-
Execute no PowerShell:
[Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) -
Verifique as variáveis de ambiente:
[Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Inicializar um cliente
Após inicializar o cliente, liste as tabelas da instância para verificar a conexão.
O acesso pela rede pública fica desativado por padrão em novas instâncias. Para acessar recursos da instância pela rede pública, ative o acesso à rede pública em Network Management da instância.
WideColumn
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)
func main() {
// yourInstanceName: enter your instance name
instanceName := "yourInstanceName"
// yourEndpoint: enter 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 data tables in the instance and print to console
tables, err := client.ListTable()
if err != nil {
fmt.Println("Failed to list table")
} else {
for _, table := range tables.TableNames {
fmt.Println(table)
}
}
}
TimeSeries
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)
func main() {
// yourInstanceName: enter your instance name
instanceName := "yourInstanceName"
// yourEndpoint: enter 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 time series tables in the instance and print to console
timeseriesTables, err := client.ListTimeseriesTable()
if err != nil {
fmt.Println("Failed to list table")
} else {
for _, timeseriesTablesMeta := range timeseriesTables.GetTimeseriesTableMeta() {
fmt.Println(timeseriesTablesMeta.GetTimeseriesTableName())
}
}
}
Compatibilidade de versões
A versão mais recente é a 1,17.x. Todas as versões mantêm compatibilidade retroativa.
Para consultar o changelog do SDK, veja Histórico de versões do Tablestore SDK for Go.
Perguntas frequentes
Referências
Para tratamento de erros no Tablestore, consulte Tratamento de erros.