全部產品
Search
文件中心

Tablestore:Java SDK

更新時間:Nov 11, 2025

Table Store Java SDK 支援寬表模型、時序模型和訊息模型操作,為Java開發人員提供完整的資料存放區和管理能力。

快速接入

通過以下步驟快速接入Table Store Java SDK,完成從環境準備到用戶端驗證的完整流程。

準備環境

下載和安裝Java運行環境(Java 6及以上版本),通過 java -version 命令查看Java版本資訊。

安裝SDK

根據開發環境選擇合適的安裝方式。推薦使用最新版本的SDK,確保程式碼範例正常運行。

添加Maven依賴(推薦)

在Maven專案中使用Table Store Java SDK,只需在 pom.xml 檔案中加入相應依賴即可。

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

Eclipse專案匯入JAR包

對於未使用Maven構建工具的專案,可通過手動匯入JAR包的方式整合SDK。

  1. 下載Java SDK開發包

  2. 解壓該開發包。

  3. 在Eclipse中選擇專案,右鍵選擇Properties > Java Build Path > Libraries > Add External JARs

  4. 進入第2步解壓後的開發包檔案夾,依次選擇tablestore-5.17.7.jarlib檔案夾下的所有JAR包,單擊開啟,匯入JAR包。

  5. 確認Libraries下已匯入上述所有JAR包,單擊Apply and Close,應用專案配置。

    說明

    如果使用的是JavaSE-9及以上版本,請將JAR包匯入在LibrariesModulepath下。

配置訪問憑證

為阿里雲帳號或RAM使用者建立AccessKey,並按如下方式將AccessKey配置到環境變數中。通過環境變數配置AccessKey可避免在代碼中寫入程式碼敏感資訊,提升安全性。

配置完成後請重啟或重新整理編譯運行環境,包括IDE、命令列介面、其它傳統型應用程式及後台服務,確保最新的系統內容變數成功載入。更多訪問憑證類型,請參見配置訪問憑證

Linux

  1. 在命令列介面執行以下命令來將環境變數設定追加到 ~/.bashrc 檔案中。

    echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
  2. 執行以下命令使變更生效。

    source ~/.bashrc
  3. 執行以下命令檢查環境變數是否生效。

    echo $TABLESTORE_ACCESS_KEY_ID
    echo $TABLESTORE_ACCESS_KEY_SECRET

macOS

  1. 在終端中執行以下命令,查看預設 Shell 類型。

    echo $SHELL
  2. 根據預設 Shell 類型進行操作。

    Zsh

    1. 執行以下命令來將環境變數設定追加到 ~/.zshrc 檔案中。

      echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
    2. 執行以下命令使變更生效。

      source ~/.zshrc
    3. 執行以下命令檢查環境變數是否生效。

      echo $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET

    Bash

    1. 執行以下命令來將環境變數設定追加到 ~/.bash_profile 檔案中。

      echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
      echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
    2. 執行以下命令使變更生效。

      source ~/.bash_profile
    3. 執行以下命令檢查環境變數是否生效。

      echo $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET

Windows

CMD

  1. 在CMD中運行以下命令設定環境變數。

    setx TABLESTORE_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. 重啟CMD後,運行以下命令,檢查環境變數是否生效。

    echo %TABLESTORE_ACCESS_KEY_ID%
    echo %TABLESTORE_ACCESS_KEY_SECRET%

PowerShell

  1. 在PowerShell中運行以下命令。

    [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. 運行以下命令,檢查環境變數是否生效。

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

初始化用戶端

以下樣本使用V4簽名和同步方式初始化用戶端,並通過列舉Table Store執行個體下的資料表進行串連驗證。

用戶端具備安全執行緒特性,內部自動管理線程池和串連資源。在多線程環境中建議共用一個用戶端執行個體,避免為每個線程或請求重複建立用戶端對象。
重要

新建立的執行個體預設未啟用公網訪問功能。如果需要通過公網訪問執行個體中的資源,請在執行個體的網路管理中設定允許公網訪問。

寬表模型

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) {
        
        // 從環境變數中擷取訪問憑證(需要配置TABLESTORE_ACCESS_KEY_ID和TABLESTORE_ACCESS_KEY_SECRET)
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: 根據執行個體資訊修改以下配置
        final String region = "cn-hangzhou"; // 填寫執行個體所屬的地區ID,例如 "cn-hangzhou"
        final String instanceName = "n01k********"; // 填寫執行個體名稱
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // 填寫執行個體訪問地址

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

            // 建立用戶端執行個體
            client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // 列舉所有資料表
            ListTableResponse listTableResponse = client.listTable();

            // 輸出資料表列表資訊
            System.out.println("在執行個體 '" + instanceName + "' 中共找到 " + listTableResponse.getTableNames().size() + " 個資料表:");

            listTableResponse.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("列舉資料表失敗,詳細資料如下:");
            e.printStackTrace();
        } finally {
            // 關閉用戶端
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

時序模型

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) {
        
        // 從環境變數中擷取訪問憑證(需要配置TABLESTORE_ACCESS_KEY_ID和TABLESTORE_ACCESS_KEY_SECRET)
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: 根據執行個體資訊修改以下配置
        final String region = "cn-hangzhou"; // 填寫執行個體所屬的地區ID,例如 "cn-hangzhou"
        final String instanceName = "n01k********"; // 填寫執行個體名稱
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // 填寫執行個體訪問地址

        TimeseriesClient client = null;
        try {
            // 構造V4簽名憑證
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // 建立時序用戶端執行個體
            client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // 列舉所有時序表
            ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();

            // 輸出時序表列表資訊
            System.out.println("在執行個體 '" + instanceName + "' 中共找到 " + listTimeseriesTableResponse.getTimeseriesTableNames().size() + " 個時序表:");

            listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("列舉時序表失敗,詳細資料如下:");
            e.printStackTrace();
        } finally {
            // 關閉用戶端
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

用戶端配置

Table StoreJava SDK支援同步和非同步兩種用戶端模式,可根據應用情境選擇合適的用戶端類型。非同步用戶端能夠提供更好的並發處理能力,適合高輸送量情境。

非同步用戶端

非同步用戶端通過回調機制處理請求結果,避免線程阻塞,提升應用程式的並發處理能力。

寬表模型

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) {
        
        // 從環境變數中擷取訪問憑證(需要配置TABLESTORE_ACCESS_KEY_ID和TABLESTORE_ACCESS_KEY_SECRET)
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: 根據執行個體資訊修改以下配置
        final String region = "cn-hangzhou"; // 填寫執行個體所屬的地區ID,例如 "cn-hangzhou"
        final String instanceName = "n01k********"; // 填寫執行個體名稱
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // 填寫執行個體訪問地址

        AsyncClient client = null;
        try {
            // 構造V4簽名憑證
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // 建立非同步用戶端執行個體
            client = new AsyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // 使用 CompletableFuture 進行非同步處理
            CompletableFuture<ListTableResponse> future = new CompletableFuture<>();

            // 在回調中處理非同步結果
            client.listTable(new TableStoreCallback<ListTableRequest, ListTableResponse>() {
                @Override
                public void onCompleted(ListTableRequest req, ListTableResponse res) {
                    System.out.println("非同步請求成功完成。");
                    future.complete(res); // 非同步作業成功時,完成Future
                }
                @Override
                public void onFailed(ListTableRequest req, Exception ex) {
                    System.err.println("非同步請求失敗。");
                    future.completeExceptionally(ex); // 非同步作業失敗時,用異常完成Future
                }
            });

            System.out.println("已發起 listTable 非同步請求,等待結果...");

            // 阻塞等待結果,並設定逾時
            // 在實際應用中,可以繼續執行其他非阻塞任務,或將 future 傳遞給其他流程
            ListTableResponse response = future.get(5, TimeUnit.SECONDS);

            // 在主線程中處理成功的結果
            System.out.println("在執行個體 '" + instanceName + "' 中共找到 " + response.getTableNames().size() + " 個資料表:");
            response.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("列舉資料表失敗,詳細資料如下:");
            e.printStackTrace();
        } finally {
            // 關閉用戶端
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

時序模型

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) {
        
        // 從環境變數中擷取訪問憑證(需要配置TABLESTORE_ACCESS_KEY_ID和TABLESTORE_ACCESS_KEY_SECRET)
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: 根據執行個體資訊修改以下配置
        final String region = "cn-hangzhou"; // 填寫執行個體所屬的地區ID,例如 "cn-hangzhou"
        final String instanceName = "n01k********"; // 填寫執行個體名稱
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // 填寫執行個體訪問地址

        AsyncTimeseriesClient client = null;
        try {
            // 構造V4簽名憑證
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
            CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

            // 建立非同步時序用戶端執行個體
            client = new AsyncTimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // 使用 CompletableFuture 進行非同步處理
            CompletableFuture<ListTimeseriesTableResponse> future = new CompletableFuture<>();

            // 在回調中處理非同步結果
            client.listTimeseriesTable(new TableStoreCallback<ListTimeseriesTableRequest, ListTimeseriesTableResponse>() {
                @Override
                public void onCompleted(ListTimeseriesTableRequest req, ListTimeseriesTableResponse res) {
                    System.out.println("非同步請求成功完成。");
                    future.complete(res); // 非同步作業成功時,完成Future
                }
                @Override
                public void onFailed(ListTimeseriesTableRequest req, Exception ex) {
                    System.err.println("非同步請求失敗。");
                    future.completeExceptionally(ex); // 非同步作業失敗時,用異常完成Future
                }
            });

            System.out.println("已發起 listTimeseriesTable 非同步請求,等待結果...");

            // 阻塞等待結果,並設定逾時
            // 在實際應用中,可以繼續執行其他非阻塞任務,或將 future 傳遞給其他流程
            ListTimeseriesTableResponse response = future.get(5, TimeUnit.SECONDS);

            // 在主線程中處理成功的結果
            if (response.getTimeseriesTableNames() != null) {
                System.out.println("在執行個體 '" + instanceName + "' 中共找到 " + response.getTimeseriesTableNames().size() + " 個時序表:");
                response.getTimeseriesTableNames().forEach(System.out::println);
            }
        } catch (Exception e) {
            System.err.println("列舉時序表失敗,詳細資料如下:");
            e.printStackTrace();
        } finally {
            // 關閉用戶端
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

簽名版本

Table StoreJava SDK從5.16.1版本開始支援V4簽名。V4簽名採用更強的密碼編譯演算法和簽名機制,提升安全性,建議升級SDK版本並使用V4簽名。以下為使用V2簽名初始化用戶端的範例程式碼。

寬表模型

同步

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) {
        
        // 從環境變數中擷取訪問憑證(需要配置TABLESTORE_ACCESS_KEY_ID和TABLESTORE_ACCESS_KEY_SECRET)
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: 根據執行個體資訊修改以下配置
        final String instanceName = "n01k********"; // 填寫執行個體名稱
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // 填寫執行個體訪問地址

        SyncClient client = null;
        try {
            // 構造V2簽名憑證
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // 建立用戶端執行個體
            client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // 列舉所有資料表
            ListTableResponse listTableResponse = client.listTable();

            // 輸出資料表列表資訊
            System.out.println("在執行個體 '" + instanceName + "' 中共找到 " + listTableResponse.getTableNames().size() + " 個資料表:");

            listTableResponse.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("列舉資料表失敗,詳細資料如下:");
            e.printStackTrace();
        } finally {
            // 關閉用戶端
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

非同步

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) {
        
        // 從環境變數中擷取訪問憑證(需要配置TABLESTORE_ACCESS_KEY_ID和TABLESTORE_ACCESS_KEY_SECRET)
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: 根據執行個體資訊修改以下配置
        final String instanceName = "n01k********"; // 填寫執行個體名稱
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // 填寫執行個體訪問地址

        AsyncClient client = null;
        try {
            // 構造V2簽名憑證
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // 建立非同步用戶端執行個體
            client = new AsyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // 使用 CompletableFuture 進行非同步處理
            CompletableFuture<ListTableResponse> future = new CompletableFuture<>();

            // 在回調中處理非同步結果
            client.listTable(new TableStoreCallback<ListTableRequest, ListTableResponse>() {
                @Override
                public void onCompleted(ListTableRequest req, ListTableResponse res) {
                    System.out.println("非同步請求成功完成。");
                    future.complete(res); // 非同步作業成功時,完成Future
                }
                @Override
                public void onFailed(ListTableRequest req, Exception ex) {
                    System.err.println("非同步請求失敗。");
                    future.completeExceptionally(ex); // 非同步作業失敗時,用異常完成Future
                }
            });

            System.out.println("已發起 listTable 非同步請求,等待結果...");

            // 阻塞等待結果,並設定逾時
            // 在實際應用中,可以繼續執行其他非阻塞任務,或將 future 傳遞給其他流程
            ListTableResponse response = future.get(5, TimeUnit.SECONDS);

            // 在主線程中處理成功的結果
            System.out.println("在執行個體 '" + instanceName + "' 中共找到 " + response.getTableNames().size() + " 個資料表:");
            response.getTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("列舉資料表失敗,詳細資料如下:");
            e.printStackTrace();
        } finally {
            // 關閉用戶端
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

時序模型

同步

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) {
        
        // 從環境變數中擷取訪問憑證(需要配置TABLESTORE_ACCESS_KEY_ID和TABLESTORE_ACCESS_KEY_SECRET)
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: 根據執行個體資訊修改以下配置
        final String instanceName = "n01k********"; // 填寫執行個體名稱
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // 填寫執行個體訪問地址

        TimeseriesClient client = null;
        try {
            // 構造V2簽名憑證
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // 建立時序用戶端執行個體
            client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // 列舉所有時序表
            ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();

            // 輸出時序表列表資訊
            System.out.println("在執行個體 '" + instanceName + "' 中共找到 " + listTimeseriesTableResponse.getTimeseriesTableNames().size() + " 個時序表:");

            listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
        } catch (Exception e) {
            System.err.println("列舉時序表失敗,詳細資料如下:");
            e.printStackTrace();
        } finally {
            // 關閉用戶端
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

非同步

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) {
        
        // 從環境變數中擷取訪問憑證(需要配置TABLESTORE_ACCESS_KEY_ID和TABLESTORE_ACCESS_KEY_SECRET)
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");

        // TODO: 根據執行個體資訊修改以下配置
        final String instanceName = "n01k********"; // 填寫執行個體名稱
        final String endpoint = "https://n01k********.cn-hangzhou.ots.aliyuncs.com"; // 填寫執行個體訪問地址

        AsyncTimeseriesClient client = null;
        try {
            // 構造V2簽名憑證
            DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
            CredentialsProvider provider = new DefaultCredentialProvider(credentials);

            // 建立非同步時序用戶端執行個體
            client = new AsyncTimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

            // 使用 CompletableFuture 進行非同步處理
            CompletableFuture<ListTimeseriesTableResponse> future = new CompletableFuture<>();

            // 在回調中處理非同步結果
            client.listTimeseriesTable(new TableStoreCallback<ListTimeseriesTableRequest, ListTimeseriesTableResponse>() {
                @Override
                public void onCompleted(ListTimeseriesTableRequest req, ListTimeseriesTableResponse res) {
                    System.out.println("非同步請求成功完成。");
                    future.complete(res); // 非同步作業成功時,完成Future
                }
                @Override
                public void onFailed(ListTimeseriesTableRequest req, Exception ex) {
                    System.err.println("非同步請求失敗。");
                    future.completeExceptionally(ex); // 非同步作業失敗時,用異常完成Future
                }
            });

            System.out.println("已發起 listTimeseriesTable 非同步請求,等待結果...");

            // 阻塞等待結果,並設定逾時
            // 在實際應用中,可以繼續執行其他非阻塞任務,或將 future 傳遞給其他流程
            ListTimeseriesTableResponse response = future.get(5, TimeUnit.SECONDS);

            // 在主線程中處理成功的結果
            if (response.getTimeseriesTableNames() != null) {
                System.out.println("在執行個體 '" + instanceName + "' 中共找到 " + response.getTimeseriesTableNames().size() + " 個時序表:");
                response.getTimeseriesTableNames().forEach(System.out::println);
            }
        } catch (Exception e) {
            System.err.println("列舉時序表失敗,詳細資料如下:");
            e.printStackTrace();
        } finally {
            // 關閉用戶端
            if (client != null) {
                client.shutdown();
            }
        }
    }
}

版本相容性

當前最新版本為5.x.x版本,新版本對歷史版本的相容性說明如下:

  • 對4.x.x系列SDK:相容

  • 對2.x.x系列SDK:不相容

常見問題

使用SDK時出現PB庫依賴衝突?

使用SDK時,如果出現了java.lang.ExceptionInInitializerError等錯誤,可能是專案中存在PB庫依賴衝突。如何解決衝突,請參見使用Java SDK時出現PB庫衝突

使用SDK時出現Signature mismatch異常?

使用SDK進行功能操作時出現如下異常:

Error Code: OTSAuthFailed, Message: Signature mismatch., RequestId: 0005f55a-xxxx-xxxx-xxxx-xxxxxxxxxxxx, TraceId: 10b0f0e0-xxxx-xxxx-xxxx-xxxxxxxxxxxx, HttpStatus: 403
  • 問題原因:初始化用戶端時設定的AccessKey ID或者AccessKey Secret不匹配。

  • 解決方案:填寫正確的AccessKey(包括AccessKey ID及AccessKey Secret)。

使用SDK時出現Request denied by instance ACL policies異常?

使用SDK訪問Table Store執行個體中的資源時出現Request denied by instance ACL policies異常。報錯樣本如下:

[ErrorCode]:OTSAuthFailed, [Message]:Request denied by instance ACL policies., [RequestId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [TraceId]:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, [HttpStatus:]403
  • 問題原因:用戶端所用的網路類型不符合執行個體的網路訪問要求。例如用戶端所用的網路類型為公網,但執行個體未設定允許通過公網進行訪問。

  • 解決方案:新建立的執行個體預設未開啟公網訪問功能,如果要使用公網訪問執行個體中的資源,可按以下步驟開啟公網訪問。

    1. 前往Table Store控制台,單擊執行個體別名。

    2. 單擊網路管理允許網路類型勾選公網,然後單擊設定

使用SDK時出現Request denied because this instance can only be accessed from the binded VPC異常?

使用SDK訪問Table Store執行個體中的資源時出現Request denied because this instance can only be accessed from the binded VPC異常。報錯樣本如下:

[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
  • 問題原因:在設定Table Store執行個體的訪問類型為限定綁定VPC訪問限定控制台或綁定VPC訪問後,需要為該執行個體綁定VPC,並且確保執行個體與用戶端位於同一VPC中,通過VPC地址訪問Table Store。

  • 解決方案:修改執行個體的訪問類型支援公網訪問,或者將VPC綁定到Table Store執行個體並確保用戶端位於該VPC網路下。VPC綁定方式:

    1. 前往Table Store控制台,單擊執行個體別名。

    2. 單擊網路管理 > 綁定VPC,選擇VPC交換器,並填寫VPC名稱,然後單擊確定

使用SDK時出現SocketTimeoutException異常?

由於網路不通或網路抖動、伺服器高負載、用戶端Full GC等原因可能會導致用戶端訪問Table Store逾時。當出現用戶端訪問逾時的問題時,需要通過檢查網路連通性、伺服器延遲、用戶端是否出現Full GC問題等操作來解決該問題。更多資訊,請參見使用Java SDK訪問Table Store時出現SocketTimeoutException異常

使用SDK時出現The access key id is invalid異常?

使用SDK時出現如下異常:

java.lang.IllegalArgumentException: The access key id is invalid:xxx.
  • 問題原因:AccessKey(包括AccessKey ID和AccessKey Secret)設定不正確,傳入了非法字元。

  • 解決方案:設定正確的AccessKey資訊。

使用SDK時出現java.lang.IllegalStateException:Request cannot be executed; I/O reactor status:STOPPED異常?

使用SDK時出現如下異常:

java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED
  • 問題原因:一般是由於用戶端被調用了shutDown,其內部的I/O reactor均已被關閉。

  • 解決方案:調用的用戶端不能處於shutDown狀態。如果調用的用戶端已處於shutDown狀態,請重新初始化再進行操作。

相關文檔