Tablestore Java SDK は、ワイドカラムモデル、時系列モデル、メッセージモデルの操作をサポートしています。Java 開発者に包括的なデータストレージと管理機能を提供します。
クイックインテグレーション
以下の手順に従って、Tablestore Java SDK を迅速に統合します。このガイドでは、環境の準備からクライアント接続の確認までの全プロセスを説明します。
環境の準備
Java ランタイム環境 (Java 6 以降) をダウンロードしてインストールします。 java -version コマンドを実行して、Java のバージョンを確認できます。
SDK のインストール
開発環境に基づいてインストール方法を選択できます。コード例が正しく実行されるように、最新の SDK バージョンを使用することを推奨します。
Maven 依存関係の追加 (推奨)
Maven プロジェクトで Tablestore Java SDK を使用するには、次の依存関係を pom.xml ファイルに追加します。
<dependency>
<groupId>com.aliyun.openservices</groupId>
<artifactId>tablestore</artifactId>
<version>5.17.7</version>
</dependency>Eclipse プロジェクトへの JAR パッケージのインポート
Maven を使用しないプロジェクトの場合、JAR パッケージを手動でインポートすることで SDK を統合できます。
Java SDK パッケージをダウンロードします。
パッケージを解凍します。
Eclipse で、プロジェクトを右クリックし、 を選択します。
ステップ 2 で解凍したパッケージフォルダに移動します。
tablestore-5.17.7.jarファイルとlibフォルダ内のすべての JAR ファイルを選択します。[開く] をクリックして JAR パッケージをインポートします。すべての JAR パッケージが
[ライブラリ]の下にインポートされていることを確認します。[適用して閉じる] をクリックしてプロジェクト設定を適用します。説明Java SE 9 以降を使用する場合、
Librariesの下のModulepathに JAR パッケージをインポートする必要があります。
アクセス認証情報の設定
Alibaba Cloud アカウントまたは RAM ユーザーの AccessKey を作成できます。次に、以下に示すように環境変数に AccessKey を設定します。環境変数に AccessKey を設定すると、機密情報がコードにハードコーディングされるのを防ぐことができるため、セキュリティが向上します。
設定が完了したら、IDE、コマンドラインインターフェイス、その他のデスクトップアプリケーション、バックグラウンドサービスなど、開発環境を再起動またはリフレッシュする必要があります。これにより、最新のシステム環境変数が確実に読み込まれます。他の種類のアクセス認証情報の詳細については、「アクセス認証情報の設定」をご参照ください。
Linux
次のコマンドを実行して、環境変数の設定を
~/.bashrcファイルに追加します。echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc次のコマンドを実行して変更を適用します。
source ~/.bashrc次のコマンドを実行して、環境変数が有効であることを確認します。
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
macOS
ターミナルで次のコマンドを実行して、デフォルトのシェルタイプを表示します。
echo $SHELLデフォルトのシェルタイプに基づいて、次の操作を実行します。
Zsh
次のコマンドを実行して、環境変数の設定を
~/.zshrcファイルに追加します。echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc次のコマンドを実行して変更を適用します。
source ~/.zshrc次のコマンドを実行して、環境変数が有効であることを確認します。
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
Bash
次のコマンドを実行して、環境変数の設定を
~/.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次のコマンドを実行して変更を適用します。
source ~/.bash_profile次のコマンドを実行して、環境変数が有効であることを確認します。
echo $TABLESTORE_ACCESS_KEY_ID echo $TABLESTORE_ACCESS_KEY_SECRET
Windows
CMD
コマンドプロンプト (CMD) で次のコマンドを実行して、環境変数を設定します。
setx TABLESTORE_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"CMD を再起動し、次のコマンドを実行して、環境変数が有効であることを確認します。
echo %TABLESTORE_ACCESS_KEY_ID% echo %TABLESTORE_ACCESS_KEY_SECRET%
PowerShell
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)次のコマンドを実行して、環境変数が有効であることを確認します。
[Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
クライアントの初期化
以下の例は、V4 署名を使用して同期クライアントを初期化する方法を示しています。Tablestore インスタンス内のデータテーブルをリスト表示することで、接続を確認できます。
クライアントはスレッドセーフであり、内部のスレッドプールと接続リソースを自動的に管理します。マルチスレッド環境では、単一のクライアントインスタンスを共有する必要があります。スレッドまたはリクエストごとに新しいクライアントオブジェクトを作成しないでください。
デフォルトでは、新しいインスタンスのパブリックネットワークアクセスは無効になっています。インターネット経由でインスタンス内のリソースにアクセスするには、インスタンスの [ネットワーク管理] ページでパブリックネットワークアクセスを有効にする必要があります。
ワイドカラムモデル
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("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 {
// クライアントをシャットダウンします。
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("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 {
// クライアントをシャットダウンします。
if (client != null) {
client.shutdown();
}
}
}
}
クライアント設定
Tablestore 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("Asynchronous request completed successfully.");
future.complete(res); // 非同期操作が成功した場合、Future を完了します。
}
@Override
public void onFailed(ListTableRequest req, Exception ex) {
System.err.println("Asynchronous request failed.");
future.completeExceptionally(ex); // 非同期操作が失敗した場合、例外で Future を完了します。
}
});
System.out.println("Asynchronous listTable request sent. Waiting for result...");
// 結果をブロックして待機し、タイムアウトを設定します。
// 実際のアプリケーションでは、他の非ブロッキングタスクを実行し続けるか、future を他のプロセスに渡すことができます。
ListTableResponse response = future.get(5, TimeUnit.SECONDS);
// メインスレッドで成功した結果を処理します。
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 {
// クライアントをシャットダウンします。
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("Asynchronous request completed successfully.");
future.complete(res); // 非同期操作が成功した場合、Future を完了します。
}
@Override
public void onFailed(ListTimeseriesTableRequest req, Exception ex) {
System.err.println("Asynchronous request failed.");
future.completeExceptionally(ex); // 非同期操作が失敗した場合、例外で Future を完了します。
}
});
System.out.println("Asynchronous listTimeseriesTable request sent. Waiting for result...");
// 結果をブロックして待機し、タイムアウトを設定します。
// 実際のアプリケーションでは、他の非ブロッキングタスクを実行し続けるか、future を他のプロセスに渡すことができます。
ListTimeseriesTableResponse response = future.get(5, TimeUnit.SECONDS);
// メインスレッドで成功した結果を処理します。
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 {
// クライアントをシャットダウンします。
if (client != null) {
client.shutdown();
}
}
}
}
署名バージョン
Tablestore Java 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("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 {
// クライアントをシャットダウンします。
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("Asynchronous request completed successfully.");
future.complete(res); // 非同期操作が成功した場合、Future を完了します。
}
@Override
public void onFailed(ListTableRequest req, Exception ex) {
System.err.println("Asynchronous request failed.");
future.completeExceptionally(ex); // 非同期操作が失敗した場合、例外で Future を完了します。
}
});
System.out.println("Asynchronous listTable request sent. Waiting for result...");
// 結果をブロックして待機し、タイムアウトを設定します。
// 実際のアプリケーションでは、他の非ブロッキングタスクを実行し続けるか、future を他のプロセスに渡すことができます。
ListTableResponse response = future.get(5, TimeUnit.SECONDS);
// メインスレッドで成功した結果を処理します。
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 {
// クライアントをシャットダウンします。
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("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 {
// クライアントをシャットダウンします。
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("Asynchronous request completed successfully.");
future.complete(res); // 非同期操作が成功した場合、Future を完了します。
}
@Override
public void onFailed(ListTimeseriesTableRequest req, Exception ex) {
System.err.println("Asynchronous request failed.");
future.completeExceptionally(ex); // 非同期操作が失敗した場合、例外で Future を完了します。
}
});
System.out.println("Asynchronous listTimeseriesTable request sent. Waiting for result...");
// 結果をブロックして待機し、タイムアウトを設定します。
// 実際のアプリケーションでは、他の非ブロッキングタスクを実行し続けるか、future を他のプロセスに渡すことができます。
ListTimeseriesTableResponse response = future.get(5, TimeUnit.SECONDS);
// メインスレッドで成功した結果を処理します。
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 {
// クライアントをシャットダウンします。
if (client != null) {
client.shutdown();
}
}
}
}
バージョン互換性
最新バージョンは 5.x.x です。最新バージョンと以前のバージョンの互換性は次のとおりです:
4.x.x シリーズの SDK は互換性があります。
Tablestore Java SDK V2.x.x:互換性なし
よくある質問
SDK の使用時に PB ライブラリの依存関係の競合が発生した場合はどうすればよいですか?
SDK の使用時に java.lang.ExceptionInInitializerError などのエラーが発生した場合、プロジェクトに Protocol Buffers (PB) ライブラリの依存関係の競合が存在する可能性があります。この競合を解決するには、「Java SDK 使用時の PB ライブラリの競合」をご参照ください。
SDK の使用時に「Signature mismatch」例外が発生した場合はどうすればよいですか?
次の例外が発生します:
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 ID と AccessKey Secret を含む正しい AccessKey を指定してください。
SDK の使用時に「Request denied by instance ACL policies」例外が発生した場合はどうすればよいですか?
SDK を使用して Tablestore インスタンス内のリソースにアクセスすると、次の 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原因:クライアントが使用するネットワークタイプが、インスタンスのネットワークアクセス要件を満たしていません。たとえば、クライアントはインターネットを使用していますが、インスタンスはインターネット経由のアクセスを許可するように設定されていません。
解決策:デフォルトでは、新しいインスタンスのパブリックネットワークアクセスは無効になっています。インターネット経由でインスタンス内のリソースにアクセスするには、次のようにパブリックネットワークアクセスを有効にできます:
Tablestore コンソールに移動し、インスタンスのエイリアスをクリックします。
[ネットワーク管理] をクリックします。[許可するネットワークタイプ] で [インターネット] を選択し、[設定] をクリックします。
SDK の使用時に「Request denied because this instance can only be accessed from the binded VPC」例外が発生した場合はどうすればよいですか?
SDK を使用して Tablestore インスタンス内のリソースにアクセスすると、次の Request denied because this instance can only be accessed from the bound 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原因:Tablestore インスタンスのアクセスタイプが [バインドされた VPC のみ] または [コンソールまたはバインドされた VPC のみ] に設定されている場合、インスタンスに VPC をアタッチする必要があります。また、クライアントがインスタンスと同じ VPC 内にあり、VPC エンドポイントを使用して Tablestore にアクセスしていることを確認する必要があります。
解決策:インスタンスのアクセスタイプを変更してインターネットアクセスを許可するか、Tablestore インスタンスに VPC をアタッチし、クライアントがその VPC ネットワーク内にあることを確認します。VPC をアタッチするには:
Tablestore コンソールに移動し、インスタンスのエイリアスをクリックします。
をクリックします。[VPC] と [VSwitch] を選択し、[VPC 名] を入力してから [OK] をクリックします。
SDK の使用時に SocketTimeoutException が発生した場合はどうすればよいですか?
ネットワーク接続の失敗、ネットワークジッター、高いサーバー負荷、またはクライアントでのフルガベージコレクション (GC) が原因で、クライアントが Tablestore にアクセスする際にタイムアウトすることがあります。この問題を解決するには、ネットワーク接続、サーバーのレイテンシ、およびクライアントでフル GC が発生したかどうかを確認できます。詳細については、「Java SDK を使用して Tablestore にアクセスする際に SocketTimeoutException が発生した場合はどうすればよいですか?」をご参照ください。
SDK の使用時に「The access key id is invalid」例外が発生した場合はどうすればよいですか?
SDK の使用時に次の例外が発生します:
java.lang.IllegalArgumentException: The access key id is invalid:xxx.原因:AccessKey ID と AccessKey Secret を含む AccessKey が正しくないか、無効な文字が含まれています。
解決策:正しい 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 リアクターが閉じられています。解決策:クライアントが呼び出されるとき、
shutDown状態であってはなりません。クライアントがshutDown状態の場合、操作を実行する前に再初期化してください。