Tüm Ürünler
Search
Belge Merkezi

Tablestore:Java SDK

Son Güncelleme:Oct 02, 2026

Tablestore Java SDK; geniş sütun, zaman serisi ve mesaj modeli işlemlerini destekler.

Hızlı entegrasyon

Ortam kurulumundan istemci doğrulamasına kadar Tablestore Java SDK entegrasyonunu tamamlayın.

image

Ortamı hazırlayın

Java çalışma zamanını (Java 6 veya üzeri) yükleyin. Doğrulamak için java -version komutunu çalıştırın.

SDK'yı yükleyin

Kod örneklerinin doğru çalışmasını sağlamak için SDK'nın en son sürümünü kullanın.

Maven bağımlılığı ekleyin (Önerilen)

Tablestore Java SDK'yı bir Maven projesinde kullanmak için aşağıdaki bağımlılığı pom.xml dosyanıza ekleyin.

<dependency>
    <groupId>com.aliyun.openservices</groupId>
    <artifactId>tablestore</artifactId>
    <version>5.17.7</version>
</dependency>

JAR paketlerini Eclipse projesine aktarın

Maven olmayan projeler için JAR paketlerini manuel olarak aktarın.

  1. Java SDK paketini indirin.

  2. Paketi ZIP'ten çıkarın.

  3. Eclipse'te projenize sağ tıklayın ve Properties > Java Build Path > Libraries > Add External JARs seçeneğini belirleyin.

  4. ZIP'ten çıkarılan paketteki tablestore-5.17.7.jar dosyasını ve lib klasöründeki tüm JAR dosyalarını seçin, ardından Open tıklayın.

  5. JAR paketlerinin Libraries altında göründüğünü doğrulayın ve Apply and Close tıklayın.

    Not

    Java SE 9 veya sonraki bir sürümü kullanıyorsanız, JAR paketlerini Libraries altındaki Modulepath konumuna aktarmanız gerekir.

Erişim kimlik bilgilerini yapılandırın

Alibaba Cloud hesabınız veya RAM kullanıcınız için bir AccessKey oluşturun ve kimlik bilgilerinin kod içinde sabit olarak yer almasını önlemek amacıyla bunları ortam değişkeni olarak yapılandırın.

Güncellenmiş ortam değişkenlerinin yüklenmesi için yapılandırmadan sonra IDE'nizi, terminalinizi, diğer masaüstü uygulamalarınızı ve arka plan hizmetlerinizi yeniden başlatın. Diğer erişim kimlik bilgisi türleri hakkında daha fazla bilgi için bkz. Erişim kimlik bilgilerini yapılandırma .

Linux

  1. Ortam değişkenlerini ~/.bashrc dosyasına ekleyin:

    echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
  2. Değişiklikleri uygulayın:

    source ~/.bashrc
  3. Ortam değişkenlerini doğrulayın:

    echo $TABLESTORE_ACCESS_KEY_ID
    echo $TABLESTORE_ACCESS_KEY_SECRET

macOS

  1. Varsayılan kabuğunuzu kontrol edin:

    echo $SHELL
  2. Kabuk türünüze göre yapılandırma yapın:

    Zsh

    1. Ortam değişkenlerini ~/.zshrc dosyasına ekleyin:

      echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
    2. Değişiklikleri uygulayın:

      source ~/.zshrc
    3. Ortam değişkenlerini doğrulayın:

      echo $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET

    Bash

    1. Ortam değişkenlerini ~/.bash_profile dosyasına ekleyin:

      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. Değişiklikleri uygulayın:

      source ~/.bash_profile
    3. Ortam değişkenlerini doğrulayın:

      echo $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET

Windows

CMD

  1. CMD'de ortam değişkenlerini ayarlayın:

    setx TABLESTORE_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. CMD'yi yeniden başlatın ve doğrulayın:

    echo %TABLESTORE_ACCESS_KEY_ID%
    echo %TABLESTORE_ACCESS_KEY_SECRET%

PowerShell

  1. PowerShell'de aşağıdaki komutu çalıştırın:

    [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. Ortam değişkenlerini doğrulayın:

    [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

İstemciyi başlatın

V4 imzasıyla eşzamanlı bir istemci başlatın ve veri tablolarını listeleyerek bağlantıyı doğrulayın.

İstemci iş parçacığı açısından güvenlidir ve dahili iş parçacığı havuzlarını ile bağlantı kaynaklarını otomatik olarak yönetir. Her iş parçacığı veya istek için yeni bir tane oluşturmak yerine, tek bir örneği iş parçacıkları arasında paylaşın.
Önemli

Yeni örneklerde genel ağ erişimi varsayılan olarak devre dışıdır. Bir örneğe İnternet üzerinden erişmek için Network Management sayfasında bu özelliği etkinleştirin.

Geniş sütun modeli

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.ListTableResponse;

public class SyncClientV4 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String region = "cn-hangzhou"; // Specify the region ID of the instance, for example, "cn-hangzhou".
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        SyncClient client = null;
        try {
            // Construct credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // Create a client instance.
            client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // List all data tables.
            ListTableResponse listTableResponse = client.listTable();

            // Print the list of data tables.
            System.out.println("Found " + listTableResponse.getTableNames().size() + " data tables in instance '" + instanceName + "':");

            listTableResponse.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list data tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Zaman serisi modeli

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.timeseries.ListTimeseriesTableResponse;

public class TimeseriesSyncClientV4 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String region = "cn-hangzhou"; // Specify the region ID of the instance, for example, "cn-hangzhou".
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        TimeseriesClient client = null;
        try {
            // Construct V4 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // Create a timeseries client instance.
            client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // List all timeseries tables.
            ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();

            // Print the list of timeseries tables.
            System.out.println("Found " + listTimeseriesTableResponse.getTimeseriesTableNames().size() + " timeseries tables in instance '" + instanceName + "':");

            listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list timeseries tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

İstemci yapılandırması

Tablestore Java SDK eşzamanlı ve eşzamansız istemcileri destekler. Eşzamansız istemci, eşzamanlı iş yükleri için daha yüksek aktarım hızı sunar.

Eşzamansız istemci

Eşzamansız istemci, iş parçacıklarını engellemeden sonuçları işlemek için geri aramaları kullanır.

Geniş sütun modeli

import com.alicloud.openservices.tablestore.AsyncClient;
import com.alicloud.openservices.tablestore.TableStoreCallback;
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.ListTableRequest;
import com.alicloud.openservices.tablestore.model.ListTableResponse;

import java.util.concurrent.*;

public class AsyncClientV4 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String region = "cn-hangzhou"; // Specify the region ID of the instance, for example, "cn-hangzhou".
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        AsyncClient client = null;
        try {
            // Construct V4 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // Create an asynchronous client instance.
            client = new AsyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // Use CompletableFuture for asynchronous processing.
            CompletableFuture<ListTableResponse> future = new CompletableFuture<>();

            // Process the asynchronous result in the callback.
            client.listTable(new TableStoreCallback<ListTableRequest, ListTableResponse>() {
                @Override
                public void onCompleted(ListTableRequest req, ListTableResponse res) {
                    System.out.println("Asynchronous request completed successfully.");
                    future.complete(res); // Complete the Future when the asynchronous operation is successful.
                }
                @Override
                public void onFailed(ListTableRequest req, Exception ex) {
                    System.err.println("Asynchronous request failed.");
                    future.completeExceptionally(ex); // Complete the Future with an exception when the asynchronous operation fails.
                }
            });

            System.out.println("Asynchronous listTable request sent. Waiting for result...");

            // Block and wait for the result, and set a timeout.
            // In practice, continue to execute other non-blocking tasks or pass the future to other processes.
            ListTableResponse response = future.get(5, TimeUnit.SECONDS);

            // Process the successful result in the main thread.
            System.out.println("Found " + response.getTableNames().size() + " data tables in instance '" + instanceName + "':");
            response.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list data tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Zaman serisi modeli

import com.alicloud.openservices.tablestore.AsyncTimeseriesClient;
import com.alicloud.openservices.tablestore.TableStoreCallback;
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.timeseries.ListTimeseriesTableRequest;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;

import java.util.concurrent.*;

public class TimeseriesAsyncClientV4 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String region = "cn-hangzhou"; // Specify the region ID of the instance, for example, "cn-hangzhou".
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        AsyncTimeseriesClient client = null;
        try {
            // Construct V4 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // Create an asynchronous timeseries client instance.
            client = new AsyncTimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // Use CompletableFuture for asynchronous processing.
            CompletableFuture<ListTimeseriesTableResponse> future = new CompletableFuture<>();

            // Process the asynchronous result in the callback.
            client.listTimeseriesTable(new TableStoreCallback<ListTimeseriesTableRequest, ListTimeseriesTableResponse>() {
                @Override
                public void onCompleted(ListTimeseriesTableRequest req, ListTimeseriesTableResponse res) {
                    System.out.println("Asynchronous request completed successfully.");
                    future.complete(res); // Complete the Future when the asynchronous operation is successful.
                }
                @Override
                public void onFailed(ListTimeseriesTableRequest req, Exception ex) {
                    System.err.println("Asynchronous request failed.");
                    future.completeExceptionally(ex); // Complete the Future with an exception when the asynchronous operation fails.
                }
            });

            System.out.println("Asynchronous listTimeseriesTable request sent. Waiting for result...");

            // Block and wait for the result, and set a timeout.
            // In a real-world application, you can continue to execute other non-blocking tasks or pass the future to other processes.
            ListTimeseriesTableResponse response = future.get(5, TimeUnit.SECONDS);

            // Process the successful result in the main thread.
            if (response.getTimeseriesTableNames() != null) {
                System.out.println("Found " + response.getTimeseriesTableNames().size() + " timeseries tables in instance '" + instanceName + "':");
                response.getTimeseriesTableNames().forEach(System.out::println);
            }
        } catch (Exception e) {
            System.err.println("Failed to list timeseries tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

İmza sürümü

SDK 5.16.1 sürümünden itibaren kullanılabilen V4 imzaları, gelişmiş güvenlik için daha güçlü bir şifreleme algoritması ve imzalama mekanizması kullanır. Mümkünse V4'e yükseltin. Aşağıdaki kod, V2 imza başlatmayı göstermektedir.

Geniş sütun modeli

Eşzamanlı

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.ListTableResponse;

public class SyncClientV2 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        SyncClient client = null;
        try {
            // Construct V2 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // Create a client instance.
            client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // List all data tables.
            ListTableResponse listTableResponse = client.listTable();

            // Print the list of data tables.
            System.out.println("Found " + listTableResponse.getTableNames().size() + " data tables in instance '" + instanceName + "':");

            listTableResponse.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list data tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Eşzamansız

import com.alicloud.openservices.tablestore.AsyncClient;
import com.alicloud.openservices.tablestore.TableStoreCallback;
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.ListTableRequest;
import com.alicloud.openservices.tablestore.model.ListTableResponse;

import java.util.concurrent.*;

public class AsyncClientV2 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        AsyncClient client = null;
        try {
            // Construct V2 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // Create an asynchronous client instance.
            client = new AsyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // Use CompletableFuture for asynchronous processing.
            CompletableFuture<ListTableResponse> future = new CompletableFuture<>();

            // Process the asynchronous result in the callback.
            client.listTable(new TableStoreCallback<ListTableRequest, ListTableResponse>() {
                @Override
                public void onCompleted(ListTableRequest req, ListTableResponse res) {
                    System.out.println("Asynchronous request completed successfully.");
                    future.complete(res); // Complete the Future when the asynchronous operation is successful.
                }
                @Override
                public void onFailed(ListTableRequest req, Exception ex) {
                    System.err.println("Asynchronous request failed.");
                    future.completeExceptionally(ex); // Complete the Future with an exception when the asynchronous operation fails.
                }
            });

            System.out.println("Asynchronous listTable request sent. Waiting for result...");

            // Block and wait for the result, and set a timeout.
            // In practice, continue to execute other non-blocking tasks or pass the future to other processes.
            ListTableResponse response = future.get(5, TimeUnit.SECONDS);

            // Process the successful result in the main thread.
            System.out.println("Found " + response.getTableNames().size() + " data tables in instance '" + instanceName + "':");
            response.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list data tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Zaman serisi modeli

Eşzamanlı

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.timeseries.ListTimeseriesTableResponse;

public class TimeseriesSyncClientV2 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        TimeseriesClient client = null;
        try {
            // Construct V2 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // Create a timeseries client instance.
            client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // List all timeseries tables.
            ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();

            // Print the list of timeseries tables.
            System.out.println("Found " + listTimeseriesTableResponse.getTimeseriesTableNames().size() + " timeseries tables in instance '" + instanceName + "':");

            listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("Failed to list timeseries tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Eşzamansız

import com.alicloud.openservices.tablestore.AsyncTimeseriesClient;
import com.alicloud.openservices.tablestore.TableStoreCallback;
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.timeseries.ListTimeseriesTableRequest;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;

import java.util.concurrent.*;

public class TimeseriesAsyncClientV2 {
    
    public static void main(String[] args) {
        
        // Obtain access credentials from environment variables. You must configure TABLESTORE_ACCESS_KEY_ID and TABLESTORE_ACCESS_KEY_SECRET.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: Modify the following configurations as needed.
        final String instanceName = "n01k********"; // Specify the instance name.
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // Specify the instance endpoint.

        AsyncTimeseriesClient client = null;
        try {
            // Construct V2 signature credentials.
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // Create an asynchronous timeseries client instance.
            client = new AsyncTimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // Use CompletableFuture for asynchronous processing.
            CompletableFuture<ListTimeseriesTableResponse> future = new CompletableFuture<>();

            // Process the asynchronous result in the callback.
            client.listTimeseriesTable(new TableStoreCallback<ListTimeseriesTableRequest, ListTimeseriesTableResponse>() {
                @Override
                public void onCompleted(ListTimeseriesTableRequest req, ListTimeseriesTableResponse res) {
                    System.out.println("Asynchronous request completed successfully.");
                    future.complete(res); // Complete the Future when the asynchronous operation is successful.
                }
                @Override
                public void onFailed(ListTimeseriesTableRequest req, Exception ex) {
                    System.err.println("Asynchronous request failed.");
                    future.completeExceptionally(ex); // Complete the Future with an exception when the asynchronous operation fails.
                }
            });

            System.out.println("Asynchronous listTimeseriesTable request sent. Waiting for result...");

            // Block and wait for the result, and set a timeout.
            // In practice, continue to execute other non-blocking tasks or pass the future to other processes.
            ListTimeseriesTableResponse response = future.get(5, TimeUnit.SECONDS);

            // Process the successful result in the main thread.
            if (response.getTimeseriesTableNames() != null) {
                System.out.println("Found " + response.getTimeseriesTableNames().size() + " timeseries tables in instance '" + instanceName + "':");
                response.getTimeseriesTableNames().forEach(System.out::println);
            }
        } catch (Exception e) {
            System.err.println("Failed to list timeseries tables. Details:");
            e.printStackTrace();
        } finally {
            // Shut down the client.
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

Sürüm uyumluluğu

En son sürüm 5.x.x'tir. Önceki sürümlerle uyumluluk durumu şöyledir:

  • 4.x.x serisi SDK'lar uyumludur.

  • Tablestore Java SDK V2.x.x: uyumsuz

SSS

SDK kullanırken PB kitaplığı bağımlılık çakışması oluşursa ne yapmalıyım?

java.lang.ExceptionInInitializerError hatası oluşuyorsa projenizde muhtemelen Protocol Buffers (PB) kitaplığı bağımlılık çakışması vardır. Bu sorunu Java SDK kullanırken PB kitaplığı çakışmaları bölümündeki adımları izleyerek çözün.

SDK kullanırken "Signature mismatch" özel durumu oluşursa ne yapmalıyım?

Aşağıdaki özel durum oluşur:

Error Code: OTSAuthFailed, Message: Signature mismatch., RequestId: 0005f55a-xxxx-xxxx-xxxx-xxxxxxxxxxxx, TraceId: 10b0f0e0-xxxx-xxxx-xxxx-xxxxxxxxxxxx, HttpStatus: 403
  • Neden: AccessKey ID veya AccessKey secret yanlış.

  • Çözüm: Doğru AccessKey ID ve AccessKey secret değerlerini girin.

SDK kullanırken "Request denied by instance ACL policies" özel durumu oluşursa ne yapmalıyım?

SDK, Request denied by instance ACL policies hatasını döndürebilir:

[ErrorCode]:OTSAuthFailed, [Message]:Request denied by instance ACL policies., [RequestId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [TraceId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [HttpStatus:]403
  • Neden: İstemcinin ağ türü, örneğin erişim ilkesiyle eşleşmiyor. Örneğin, örnek İnternet erişimine izin vermiyor olabilir.

  • Çözüm: Genel ağ erişimi varsayılan olarak devre dışıdır. Etkinleştirmek için:

    1. Tablestore konsolunda hedef örneği tıklayın.

    2. Network Management tıklayın. Allowed Network Type için Internet seçeneğini belirleyin ve ardından Settings tıklayın.

SDK kullanırken "Request denied because this instance can only be accessed from the binded VPC" özel durumu oluşursa ne yapmalıyım?

SDK, Request denied because this instance can only be accessed from the bound VPC hatasını döndürebilir:

[ErrorCode]:OTSAuthFailed, [Message]:Request denied because this instance can only be accessed from the binded VPC., [RequestId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [TraceId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [HttpStatus:]403
  • Neden: Örnek erişim türü Bound VPCs Only veya Tablestore Console or Bound VPCs olarak ayarlanmış ancak istemci bağlı bir VPC içinde değil veya Tablestore'a bir VPC uç noktası üzerinden erişmiyor.

  • Çözüm: İnternet erişimine izin verin veya bir VPC bağlayıp istemciyi buradan bağlayın:

    1. Tablestore konsolunda hedef örneği tıklayın.

    2. Network Management > Bind VPC tıklayın. Bir VPC ID ve bir VSwitch seçin, bir VPC Name girin ve ardından OK tıklayın.

SDK kullanırken SocketTimeoutException oluşursa ne yapmalıyım?

İstemci zaman aşımları; ağ hataları, dalgalanmalar, yüksek sunucu yükü veya tam GC nedeniyle oluşabilir. Ağ bağlantısını, sunucu gecikme süresini ve GC etkinliğini kontrol edin. Java SDK ile Tablestore'a erişirken SocketTimeoutException oluşursa ne yapmalıyım?

SDK kullanırken "The access key id is invalid" özel durumu oluşursa ne yapmalıyım?

SDK'yı kullanırken aşağıdaki özel durum oluşur:

java.lang.IllegalArgumentException: The access key id is invalid:xxx.
  • Neden: AccessKey ID ve AccessKey secret'ı içeren AccessKey yanlış veya geçersiz bir karakter içeriyor.

  • Çözüm: Doğru AccessKey bilgilerini girin.

SDK kullanırken "java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED" özel durumu oluşursa ne yapmalıyım?

SDK'yı kullanırken aşağıdaki özel durum oluşur:

java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED
  • Neden: shutDown yöntemi zaten çağrılmış ve istemcinin G/Ç reaktörleri kapatılmış.

  • Çözüm: shutDown sonrası istemciyi yeniden başlatın. shutDown edilmiş bir istemci yeni isteklere hizmet edemez.

Başvurular