Security Token Service (STS) kullanarak başka bir kullanıcıya geçici bir erişim kimlik bilgisi verebilirsiniz. Kullanıcı, bu kimlik bilgisinin geçerlilik süresi içinde Tablestore kaynaklarına erişmek için bu kimlik bilgisini kullanabilir. Geçici kimlik bilgileri uzun vadeli anahtarlarınızı ifşa etmez. Süre dolduğunda otomatik olarak geçersiz hale gelirler; böylece Tablestore kaynaklarınıza erişim daha esnek ve güvenli olur.
Arka plan bilgileri
RAM rolü, belirli kaynaklara erişmek için izin verilebilen sanal bir kullanıcıdır. RAM kullanıcısından farklı olarak RAM rolünün kalıcı kimlik bilgileri (oturum açma parolası veya AccessKey çifti gibi) yoktur. Güvenilir bir varlığın (örneğin bir RAM kullanıcısının) rolü üstlenmesi gerekir. Başarılı üstlenmenin ardından güvenilir varlık, RAM rolü için geçici kimlik bilgileri—yani bir Security Token Service belirteci (STS Token)—alır ve bu belirteci kullanarak RAM rolü adına Tablestore hizmetine erişebilir.
Alibaba Cloud hesapları için RAM rolleri öncelikle hesaplar arası erişim ve geçici yetkilendirme senaryolarını ele alır. Bu konuda, aynı hesap içindeki bir RAM kullanıcısının bir RAM rolünü nasıl üstlendiğine dair bir örnek üzerinden STS geçici kimlik bilgilerini kullanarak Tablestore kaynaklarına erişim gösterilmektedir.
Yordam
STS geçici kimlik bilgilerini kullanarak Tablestore hizmetine erişmek için öncelikle üstlenilecek bir RAM rolü oluşturun ve bu role Tablestore erişim izni verin. Ardından, RAM rolünü üstlenecek bir RAM kullanıcısı oluşturun ve STS geçici kimlik bilgilerini alın. Son olarak, bu kimlik bilgilerini kullanarak Tablestore kaynaklarına istek gönderin.
1. Adım: RAM rolü oluşturma
Alibaba Cloud hesabınızla (ana hesap) veya RAM yöneticisi olarak Resource Access Management (RAM) konsoluna giriş yapın.
Sol gezinme bölmesinde seçeneğini belirterek Roles sayfasına gidin.
-
Create Role düğmesini tıklayın, güvenilir varlığı yapılandırın ve OK düğmesine tıklayın.
Parameter
Example value
Trusted entity type
Alibaba Cloud account
Trusted entity name
Current Alibaba Cloud account Create Role iletişim kutusunda Role Name alanını
RamTablestoreolarak ayarlayın ve OK düğmesine tıklayın.
STS aracılığıyla geçici kimlik bilgileri alırken RAM rolünün ARN değerini belirtmeniz gerekir. Rolün ayrıntılar sayfasındaki Basic Information bölümünden ARN değerini bulup kopyalayabilirsiniz.
Bu rolün ARN biçimi acs:ram::<Alibaba Cloud account ID>:role/ramtablestore şeklindedir. ARN değerini almak için yanındaki Copy düğmesine tıklayın.
2. Adım:Tablestoreerişim izinlerini verme
Varsayılan bir ilke kullanma
AliyunOTSFullAccess ilkesini kullanarak RAM rolüne Tablestore erişim izni verin.
AliyunOTSFullAccess ilkesi Tablestore üzerinde tam erişim sağlar. Aşağıdaki seçeneklerden birini de tercih edebilirsiniz:
Salt okunur erişim için RAM rolüne
AliyunOTSReadOnlyAccessilkesini atayın.Salt yazma erişimi için RAM rolüne
AliyunOTSWriteOnlyAccessilkesini atayın.
Sol gezinme bölmesinde seçeneğini belirleyin.
Roles sayfasında hedef RAM rolünü bulun.
RAM rolünün yanındaki Attach Policy düğmesine tıklayın veya rol adına tıklayarak ayrıntılar sayfasına gidin ve Permissions bölümündeki Grant Permission düğmesine tıklayın.
Grant Permission panelinde Access Policy bölümünde
AliyunOTSFullAccessilkesini aratın ve seçin.Confirm New Authorization düğmesine tıklayın.
Özel bir ilke kullanma
-
Özel bir ilke oluşturun.
Sol gezinme bölmesinde seçeneğini belirleyin.
Policies sayfasında Create Policy düğmesine tıklayın.
-
Create Policy sayfasında Script Editor sekmesine tıklayın, giriş kutusuna betiği girin ve OK düğmesine tıklayın.
Aşağıdaki örnek betik tek bir örneğe erişim izni verir. İhtiyaca göre ilke betiğini özelleştirin; örneğin, tablo veya API düzeyinde izinleri kontrol edin ya da IP adresi veya erişim zamanı gibi koşullara dayalı kısıtlamalar ekleyin. RAM ilkeleri hakkında daha fazla bilgi için bkz. Özel RAM ilkeleri .
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "ots:*", "Resource": "acs:ots:*:*:instance/your_instance_name*" } ] } Create Policy iletişim kutusunda
TestRAMPolicygibi bir ilke adı girin ve OK düğmesine tıklayın.
-
Özel ilkeyi RAM rolüne atayın.
Sol gezinme bölmesinde seçeneğini belirleyin.
Roles sayfasında hedef RAM rolünü bulun.
RAM rolünün yanındaki Attach Policy düğmesine tıklayın veya rol adına tıklayarak ayrıntılar sayfasına gidin ve Permissions bölümündeki Grant Permission düğmesine tıklayın.
Grant Permission panelinde Access Policy bölümünde oluşturduğunuz özel erişim ilkesini aratın ve seçin.
Confirm düğmesine tıklayın.
Rolün ayrıntılar sayfasındaki Permissions sekmesinden atanmış ilkeleri görüntüleyebilirsiniz.
3. Adım: RAM kullanıcısı oluşturma
RAM rolünü üstlenecek bir RAM kullanıcısı oluşturun.
Alibaba Cloud hesabınızı veya yönetici izinlerine sahip bir RAM kullanıcısını kullanarak RAM konsoluna giriş yapın.
Sol gezinme bölmesinde Identities > Users seçeneğini belirleyin.
Users sayfasında Create User düğmesine tıklayın.
-
Create User sayfasında User Account Information bölümünde kullanıcının temel bilgilerini yapılandırın:
Logon Name: Oturum açma adı harf, rakam, nokta (.), kısa çizgi (-) ve alt çizgi (_) içerebilir. Uzunluğu en fazla 64 karakter olabilir.
Display Name: Görünen adın uzunluğu en fazla 128 karakter olabilir.
Tag:
simgesine tıklayarak
bir etiket anahtarı ve değeri girin. Etiket eklemek, RAM kullanıcısını bulmanıza ve yönetmenize yardımcı olur.
NotBirden çok RAM kullanıcısını toplu olarak oluşturmak için Add User düğmesine tıklayabilirsiniz.
-
Access Mode bölümünde Programmatic Access seçeneğini işaretleyin ve ardından OK düğmesine tıklayın.
NotRAM kullanıcısının Alibaba Cloud Management Console'a oturum açmasına izin vermek için Console Access seçeneğini işaretleyin.
-
Actions sütununda RAM kullanıcı bilgilerini kaydetmek için Copy düğmesine tıklayın. AccessKey ID ve AccessKey secret değerlerini tek tek de kopyalayabilirsiniz.
ÖnemliAccessKey secret yalnızca oluşturma sırasında bir kez gösterilir ve daha sonra alınamaz. Hemen güvenli bir konumda saklayın.
4. Adım: RAM kullanıcısına AssumeRole çağırma izni verme
Bir RAM rolünü üstlenmek için RAM kullanıcısının AssumeRole işlemini çağırma iznine sahip olması gerekir.
Sol gezinme bölmesinde seçeneğini belirleyin.
Users sayfasında hedef RAM kullanıcısını bulun.
RAM kullanıcısının yanındaki Add Permissions düğmesine tıklayın veya kullanıcı adına tıklayarak ayrıntılar sayfasına gidin ve Permission Management sekmesindeki Grant Permission düğmesine tıklayın.
Grant Permission panelinin access policy bölümünde
AliyunSTSAssumeRoleAccessilkesini aratın ve seçin.Confirm düğmesine tıklayın.
5. Adım: RAM kullanıcısıyla RAM rolünü üstlenme ve geçici kimlik bilgilerini alma
Kaynaklara erişmeden önce RAM kullanıcısını kullanarak RAM rolünü üstlenin ve geçici kimlik bilgilerini alın. Bu kimlik bilgileri yalnızca geçerlilik süreleri boyunca kullanılabilir. Bu örnekte Java kullanılmaktadır.
Geçici kimlik bilgilerini almak için doğrudan OpenAPI Explorer'da AssumeRole işlemini çağırabilirsiniz .
Hazırlıklar
-
Aşağıdaki bağımlılığı Maven projenize ekleyin.
<dependency> <groupId>com.aliyun</groupId> <artifactId>sts20150401</artifactId> <version>1.1.6</version> </dependency> -
Ortam değişkenlerini yapılandırın. Yapılandırma tamamlandıktan sonra IDE, komut satırı arabirimi, diğer masaüstü uygulamaları ve arka plan hizmetleri dahil olmak üzere derleme ve çalışma zamanı ortamınızı yeniden başlatın veya yenileyerek en son sistem ortam değişkenlerinin başarıyla yüklendiğinden emin olun.
Linux
-
Komut satırı arabiriminde aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.bashrcdosyasına ekleyin.echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc echo "export TABLESTORE_STS_ROLE_ARN='YOUR_RAM_ROLE_ARN'" >> ~/.bashrc -
Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:
source ~/.bashrc -
Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET echo $TABLESTORE_STS_ROLE_ARN
macOS
-
Terminalde varsayılan Shell türünü kontrol etmek için aşağıdaki komutu çalıştırın.
echo $SHELL -
Varsayılan Shell türüne göre işlemleri gerçekleştirin.
Zsh
-
Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.zshrcdosyasına ekleyin.echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc echo "export TABLESTORE_STS_ROLE_ARN='YOUR_RAM_ROLE_ARN'" >> ~/.zshrc -
Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:
source ~/.zshrc -
Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET echo $TABLESTORE_STS_ROLE_ARN
Bash
-
Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.bash_profiledosyasına ekleyin.echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile echo "export TABLESTORE_STS_ROLE_ARN='YOUR_RAM_ROLE_ARN'" >> ~/.bash_profile -
Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:
source ~/.bash_profile -
Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET echo $TABLESTORE_STS_ROLE_ARN
-
Windows
CMD
-
CMD'de ortam değişkenlerini ayarlamak için aşağıdaki komutları çalıştırın.
setx ALIBABA_CLOUD_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx ALIBABA_CLOUD_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" setx TABLESTORE_STS_ROLE_ARN "YOUR_RAM_ROLE_ARN" -
CMD'yi yeniden başlattıktan sonra ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:
echo %ALIBABA_CLOUD_ACCESS_KEY_ID% echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% echo %TABLESTORE_STS_ROLE_ARN%
PowerShell
-
PowerShell'de aşağıdaki komutu çalıştırın:
[Environment]::SetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("TABLESTORE_STS_ROLE_ARN", "YOUR_RAM_ROLE_ARN", [EnvironmentVariableTarget]::User) -
Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:
[Environment]::GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("TABLESTORE_STS_ROLE_ARN", [EnvironmentVariableTarget]::User)
-
Örnek kod
Aşağıdaki örnek kod, bir RAM kullanıcısı kullanarak bir RAM rolünü üstlenir, STS geçici kimlik bilgilerini alır ve bunları konsola yazdırır. Kimlik bilgilerinin geçerlilik süresi bir saattir.
STS uç noktalarının listesi için bkz. Uç noktalar .
import com.aliyun.sts20150401.models.AssumeRoleResponse;
import com.aliyun.tea.*;
public class AssumeRoleSample {
public static com.aliyun.sts20150401.Client createClient() throws Exception {
// Leaking AccessKey credentials in source code may compromise all resources under your account. Use this sample code for reference only.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Ensure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Ensure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Endpoint for the STS service
config.endpoint = "sts.cn-hangzhou.aliyuncs.com";
return new com.aliyun.sts20150401.Client(config);
}
public static void main(String[] args) throws Exception {
com.aliyun.sts20150401.Client client = AssumeRoleSample.createClient();
com.aliyun.sts20150401.models.AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest()
// Validity period of the temporary credential, in seconds. Minimum is 900. Maximum depends on the role's maximum session duration (range: 3600–43200 seconds; default: 3600).
.setDurationSeconds(3600L)
// Required. Ensure the TABLESTORE_STS_ROLE_ARN environment variable (the RAM role ARN) is set.
.setRoleArn(System.getenv("TABLESTORE_STS_ROLE_ARN"))
// Required. A custom role session name to distinguish tokens.
.setRoleSessionName("RAMTablestore");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Obtain and print STS temporary credentials. Store them securely.
AssumeRoleResponse response = client.assumeRoleWithOptions(assumeRoleRequest, runtime);
System.out.println("Expiration: " + response.getBody().getCredentials().getExpiration());
System.out.println("Access Key Id: " + response.getBody().getCredentials().getAccessKeyId());
System.out.println("Access Key Secret: " + response.getBody().getCredentials().getAccessKeySecret());
System.out.println("Security Token: " + response.getBody().getCredentials().getSecurityToken());
} catch (TeaException error) {
// Print errors for demonstration only. Handle exceptions carefully in production code. Never ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic link
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Print errors for demonstration only. Handle exceptions carefully in production code. Never ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic link
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Diğer dillerdeki STS SDK'ları ve kod örnekleri için bkz. STS SDK'larına genel bakış.
6. Adım: Geçici erişim kimlik bilgilerini kullanarakTablestorehizmetine erişme
Hazırlıklar
Tablestore konsolunda bir örnek ve veri tabloları oluşturun.
-
Örnek adını, örnek uç noktasını ve bölge kimliğini alın.
ÖnemliYeni örneklerde varsayılan olarak genel ağ erişimi etkin değildir. Genel ağ erişimine ihtiyacınız varsa örnek için genel ağ erişimini etkinleştirin.
-
Ortam değişkenlerini yapılandırın. Yapılandırma tamamlandıktan sonra IDE, komut satırı arabirimi, diğer masaüstü uygulamaları ve arka plan hizmetleri dahil olmak üzere derleme ve çalışma zamanı ortamınızı yeniden başlatın veya yenileyerek en son sistem ortam değişkenlerinin başarıyla yüklendiğinden emin olun.
Linux
-
Komut satırı arabiriminde aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.bashrcdosyasına ekleyin.echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.bashrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.bashrc echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.bashrc -
Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:
source ~/.bashrc -
Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET echo $TABLESTORE_SESSION_TOKEN
macOS
-
Terminalde varsayılan Shell türünü kontrol etmek için aşağıdaki komutu çalıştırın.
echo $SHELL -
Varsayılan Shell türüne göre işlemleri gerçekleştirin.
Zsh
-
Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.zshrcdosyasına ekleyin.echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.zshrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.zshrc echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.zshrc -
Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:
source ~/.zshrc -
Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET echo $TABLESTORE_SESSION_TOKEN
Bash
-
Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını
~/.bash_profiledosyasına ekleyin.echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.bash_profile echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.bash_profile -
Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:
source ~/.bash_profile -
Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET echo $TABLESTORE_SESSION_TOKEN
-
Windows
CMD
-
CMD'de ortam değişkenlerini ayarlamak için aşağıdaki komutları çalıştırın.
setx TABLESTORE_ACCESS_KEY_ID "YOUR_STS_ACCESS_KEY_ID" setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_STS_ACCESS_KEY_SECRET" setx TABLESTORE_SESSION_TOKEN "YOUR_STS_TOKEN" -
CMD'yi yeniden başlattıktan sonra ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:
echo %TABLESTORE_ACCESS_KEY_ID% echo %TABLESTORE_ACCESS_KEY_SECRET% echo %TABLESTORE_SESSION_TOKEN%
PowerShell
-
PowerShell'de aşağıdaki komutu çalıştırın:
[Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", "YOUR_STS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", "YOUR_STS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("TABLESTORE_SESSION_TOKEN", "YOUR_STS_TOKEN", [EnvironmentVariableTarget]::User) -
Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:
[Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("TABLESTORE_SESSION_TOKEN", [EnvironmentVariableTarget]::User)
-
-
Kullandığınız programlama dili için Tablestore SDK'yı yükleyin.
Java
Maven kullanıyorsanız projenizin pom.xml dosyasına aşağıdaki bağımlılığı ekleyin:
<dependency> <groupId>com.aliyun.openservices</groupId> <artifactId>tablestore</artifactId> <version>5.17.4</version> </dependency>
Daha fazla bilgi için bkz. Java için Tablestore SDK'yı yükleme.
Go
Proje dizininde go.mod dosyasını oluşturmak için
go mod init <DIRNAME>komutunu çalıştırın. Ardından Go için Tablestore SDK'yı yüklemek için aşağıdaki komutu çalıştırın:Not<DIRNAME>proje dizini yolunu belirtir. <DIRNAME> ifadesini gerçek proje dizini yoluyla değiştirin.go get github.com/aliyun/aliyun-tablestore-go-sdk/tablestore
Daha fazla bilgi için bkz. Go için Tablestore SDK'yı yükleme.
Python
Python için Tablestore SDK'yı pip ile yüklemek için aşağıdaki komutu çalıştırın:
sudo pip install tablestore
Daha fazla bilgi için bkz. Python için Tablestore SDK'yı yükleme.
Node.js
Node.js için Tablestore SDK'yı yüklemek için aşağıdaki komutu çalıştırın:
npm install tablestore
Daha fazla bilgi için bkz. Node.js için Tablestore SDK'yı yükleme.
.NET
Ayrıntılar için bkz. .NET için Tablestore SDK'yı yükleme.
PHP
Ayrıntılar için bkz. PHP için Tablestore SDK'yı yükleme.
Geniş tablo modeli
Geniş tablo modelini kullanırken geniş tablo istemcisini STS geçici kimlik bilgileriyle başlatın ve istek gönderin.
Java
V4 imza (önerilen)
Aşağıdaki Java örnek kodu, V4 imza kullanarak bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.
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.*;
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 your instance region, such as cn-hangzhou
final String region = "yourRegion";
// Replace yourInstanceName with your instance name
final String instanceName = "yourInstanceName";
// Replace yourEndpoint with your instance endpoint
final String endpoint = "yourEndpoint";
// Get STS credentials from environment variables
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
final String securityToken = System.getenv("TABLESTORE_SESSION_TOKEN");
// Build V4 signature
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);
// Initialize Tablestore client
SyncClient client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// Customize ClientConfiguration if needed. Examples:
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Connection timeout in milliseconds
clientConfiguration.setSocketTimeoutInMillisecond(5000); // Socket timeout in milliseconds
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Retry strategy; default used if not set
SyncClient client = new SyncClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// List and print table names
ListTableResponse listTableResponse = client.listTable();
listTableResponse.getTableNames().forEach(System.out::println);
// Shut down Tablestore client
client.shutdown();
}
}
V2 imza
Aşağıdaki Java örnek kodu, V2 imza kullanarak bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.
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 your instance name
final String instanceName = "yourInstanceName";
// Replace yourEndpoint with your instance endpoint
final String endpoint = "yourEndpoint";
// Get STS credentials from environment variables
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
final String securityToken = System.getenv("TABLESTORE_SESSION_TOKEN");
// Build V2 signature
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
CredentialsProvider provider = new DefaultCredentialProvider(credentials);
// Initialize Tablestore client
SyncClient client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// Customize ClientConfiguration if needed. Examples:
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Connection timeout in milliseconds
clientConfiguration.setSocketTimeoutInMillisecond(5000); // Socket timeout in milliseconds
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Retry strategy; default used if not set
SyncClient client = new SyncClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// List and print table names
ListTableResponse listTableResponse = client.listTable();
listTableResponse.getTableNames().forEach(System.out::println);
// Shut down Tablestore client
client.shutdown();
}
}
Go
Aşağıdaki Go örnek kodu bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)
func main() {
// Replace yourInstanceName with your instance name
instanceName := "yourInstanceName"
// Replace yourEndpoint with your instance endpoint
endpoint := "yourEndpoint"
// Get STS credentials from environment variables
accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
securityToken := os.Getenv("TABLESTORE_SESSION_TOKEN")
// Initialize Tablestore client
client := tablestore.NewClientWithConfig(endpoint, instanceName, accessKeyId, accessKeySecret, securityToken, nil)
// List and print table names
tables, err := client.ListTable()
if err != nil {
fmt.Println("Failed to list table.")
} else {
for _, table := range (tables.TableNames) {
fmt.Println(table)
}
}
}
Python
Aşağıdaki Python örnek kodu bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.
# -*- coding: utf-8 -*-
import os
from tablestore import OTSClient
# Replace yourInstanceName with your instance name
instance_name = "yourInstanceName"
# Replace yourEndpoint with your instance endpoint
endpoint = "yourEndpoint"
# Get STS credentials from environment variables
access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID")
access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")
sts_token = os.getenv("TABLESTORE_SESSION_TOKEN")
# Initialize Tablestore client
client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name, sts_token=sts_token)
# List and print table names
resp = client.list_table()
for table_name in resp:
print(table_name)
Node.js
Aşağıdaki Node.js örnek kodu bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.
// Adjust the relative path as needed.
var TableStore = require('../index.js');
// Replace yourInstanceName with your instance name
var instancename = 'yourInstanceName';
// Replace yourEndpoint with your instance endpoint
var endpoint = 'yourEndpoint';
// Get STS credentials from environment variables
var accessKeyId = process.env.TABLESTORE_ACCESS_KEY_ID;
var accessKeySecret = process.env.TABLESTORE_ACCESS_KEY_SECRET;
var stsToken = process.env.TABLESTORE_SESSION_TOKEN;
// Initialize Tablestore client
var client = new TableStore.Client({
accessKeyId: accessKeyId,
secretAccessKey: accessKeySecret,
stsToken: stsToken,
endpoint: endpoint,
instancename: instancename
});
// List and print table names
client.listTable({}, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
console.log('success:', data);
});
PHP
Aşağıdaki PHP örnek kodu bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.
<?php
// Adjust the relative path as needed.
require (__DIR__ . '/../../vendor/autoload.php');
use Aliyun\OTS\OTSClient as OTSClient;
// Replace yourInstanceName with your instance name
$instanceName = "yourInstanceName";
// Replace yourEndpoint with your instance endpoint
$endpoint = "yourEndpoint";
// Get STS credentials from environment variables
$accessKeyId = getenv('TABLESTORE_ACCESS_KEY_ID');
$accessKeySecret = getenv('TABLESTORE_ACCESS_KEY_SECRET');
$stsToken = getenv('TABLESTORE_SESSION_TOKEN');
// Initialize Tablestore client
$client = new OTSClient(array(
'EndPoint' => $endpoint,
'AccessKeyID' => $accessKeyId,
'AccessKeySecret' => $accessKeySecret,
'InstanceName' => $instanceName,
'StsToken' => $stsToken,
));
// List and print table names
$response = $client->listTable (array ());
print json_encode ($response);
Zaman serisi modeli
Zaman serisi modelini kullanırken zaman serisi istemcisini STS geçici kimlik bilgileriyle başlatın ve istek gönderin. Zaman serisi modeli Java, Go ve Python'da desteklenir.
Java
V4 imza (önerilen)
Aşağıdaki Java örnek kodu, V4 imza kullanarak bir istemci başlatır ve örnekteki tüm zaman serisi tablo adlarını listeler.
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 your instance region, such as cn-hangzhou
final String region = "yourRegion";
// Replace yourInstanceName with your instance name
final String instanceName = "yourInstanceName";
// Replace yourEndpoint with your instance endpoint
final String endpoint = "yourEndpoint";
// Get STS credentials from environment variables
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
final String securityToken = System.getenv("TABLESTORE_SESSION_TOKEN");
// Build V4 signature
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);
// Initialize Tablestore client
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// Customize ClientConfiguration if needed. Examples:
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Connection timeout in milliseconds
clientConfiguration.setSocketTimeoutInMillisecond(5000); // Socket timeout in milliseconds
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Retry strategy; default used if not set
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// List and print time series table names
ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();
listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
// Shut down Tablestore client
client.shutdown();
}
}
V2 imza
Aşağıdaki Java örnek kodu, V2 imza kullanarak bir istemci başlatır ve örnekteki tüm zaman serisi tablo adlarını listeler.
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 your instance name
final String instanceName = "yourInstanceName";
// Replace yourEndpoint with your instance endpoint
final String endpoint = "yourEndpoint";
// Get STS credentials from environment variables
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
final String securityToken = System.getenv("TABLESTORE_SESSION_TOKEN");
// Build V2 signature
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
CredentialsProvider provider = new DefaultCredentialProvider(credentials);
// Initialize Tablestore client
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// Customize ClientConfiguration if needed. Examples:
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Connection timeout in milliseconds
clientConfiguration.setSocketTimeoutInMillisecond(5000); // Socket timeout in milliseconds
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Retry strategy; default used if not set
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// List and print time series table names
ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();
listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
// Shut down Tablestore client
client.shutdown();
}
}
Go
Aşağıdaki Go örnek kodu bir istemci başlatır ve örnekteki tüm zaman serisi tablo adlarını listeler.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)
func main() {
// Replace yourInstanceName with your instance name
instanceName := "yourInstanceName"
// Replace yourEndpoint with your instance endpoint
endpoint := "yourEndpoint"
// Get STS credentials from environment variables
accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
securityToken := os.Getenv("TABLESTORE_SESSION_TOKEN")
// Initialize Tablestore client
client := tablestore.NewTimeseriesClientWithConfig(endpoint, instanceName, accessKeyId, accessKeySecret, securityToken, nil, nil)
// List and print time series table names
timeseriesTables, err := client.ListTimeseriesTable()
if err != nil {
fmt.Println("Failed to list table.")
} else {
for _, timeseriesTablesMeta := range (timeseriesTables.GetTimeseriesTableMeta()) {
fmt.Println(timeseriesTablesMeta.GetTimeseriesTableName())
}
}
}
Python
Aşağıdaki Python örnek kodu bir istemci başlatır ve örnekteki tüm zaman serisi tablo adlarını listeler.
# -*- coding: utf-8 -*-
import os
from tablestore import OTSClient
# Replace yourInstanceName with your instance name
instance_name = "yourInstanceName"
# Replace yourEndpoint with your instance endpoint
endpoint = "yourEndpoint"
# Get STS credentials from environment variables
access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID")
access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")
sts_token = os.getenv("TABLESTORE_SESSION_TOKEN")
# Initialize Tablestore client
client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name, sts_token=sts_token)
# List and print time series table names
response = client.list_timeseries_table()
for tableMeta in response:
print(tableMeta.timeseries_table_name)