Java SDK

表格存储 Java SDK 支持宽表模型、时序模型和消息模型操作,为Java开发者提供完整的数据存储和管理能力。

快速接入

通过以下步骤快速接入表格存储 Java SDK,完成从环境准备到客户端验证的完整流程。

image

准备环境

下载和安装Java运行环境(Java 6及以上版本),通过 java -version 命令查看Java版本信息。

安装SDK

根据开发环境选择合适的安装方式。推荐使用最新版本的SDK,确保代码示例正常运行。

添加Maven依赖(推荐)

Maven项目中使用表格存储 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签名和同步方式初始化客户端,并通过列举表格存储实例下的数据表进行连接验证。

客户端具备线程安全特性,内部自动管理线程池和连接资源。在多线程环境中建议共用一个客户端实例,避免为每个线程或请求重复创建客户端对象。
重要

新创建的实例默认未启用公网访问功能。如果需要通过公网访问实例中的资源,请在实例的网络管理中设置允许公网访问。

宽表模型

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();
            }
        }
    }
}

客户端配置

表格存储Java 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();
            }
        }
    }
}

签名版本

表格存储Java SDK5.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 IDAccessKey Secret)。

使用SDK时出现Request denied by instance ACL policies异常?

使用SDK访问表格存储实例中的资源时出现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. 前往表格存储控制台,单击实例别名。

    2. 单击网络管理允许网络类型勾选公网,然后单击设置

使用SDK时出现Request denied because this instance can only be accessed from the binded VPC异常?

使用SDK访问表格存储实例中的资源时出现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
  • 问题原因:在设置表格存储实例的访问类型为限定绑定VPC访问限定控制台或绑定VPC访问后,需要为该实例绑定VPC,并且确保实例与客户端位于同一VPC中,通过VPC地址访问表格存储。

  • 解决方案:修改实例的访问类型支持公网访问,或者将VPC绑定到表格存储实例并确保客户端位于该VPC网络下。VPC绑定方式:

    1. 前往表格存储控制台,单击实例别名。

    2. 单击网络管理 > 绑定VPC,选择VPC交换机,并填写VPC名称,然后单击确定

使用SDK时出现SocketTimeoutException异常?

由于网络不通或网络抖动、服务器高负载、客户端Full GC等原因可能会导致客户端访问表格存储超时。当出现客户端访问超时的问题时,需要通过检查网络连通性、服务器延迟、客户端是否出现Full GC问题等操作来解决该问题。更多信息,请参见使用Java SDK访问表格存储时出现SocketTimeoutException异常

使用SDK时出现The access key id is invalid异常?

使用SDK时出现如下异常:

java.lang.IllegalArgumentException: The access key id is invalid:xxx.
  • 问题原因:AccessKey(包括AccessKey IDAccessKey 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状态,请重新初始化再进行操作。

相关文档