文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例。
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
AWS KMS 使用 AWS SDKs程式碼範例
下列程式碼範例示範如何 AWS Key Management Service 搭配 AWS 軟體開發套件 (SDK) 使用 。
基本概念是程式碼範例,這些範例說明如何在服務內執行基本操作。
Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境中查看內容中的動作。
開始使用
下列程式碼範例示範如何開始使用 AWS Key Management Service。
- Java
-
- SDK for Java 2.x
-
import software.amazon.awssdk.services.kms.KmsAsyncClient;
import software.amazon.awssdk.services.kms.model.ListKeysRequest;
import software.amazon.awssdk.services.kms.paginators.ListKeysPublisher;
import java.util.concurrent.CompletableFuture;
/**
* Before running this Java V2 code example, set up your development
* environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class HelloKMS {
public static void main(String[] args) {
listAllKeys();
}
public static void listAllKeys() {
KmsAsyncClient kmsAsyncClient = KmsAsyncClient.builder()
.build();
ListKeysRequest listKeysRequest = ListKeysRequest.builder()
.limit(15)
.build();
/*
* The `subscribe` method is required when using paginator methods in the AWS SDK
* because paginator methods return an instance of a `ListKeysPublisher`, which is
* based on a reactive stream. This allows asynchronous retrieval of paginated
* results as they become available. By subscribing to the stream, we can process
* each page of results as they are emitted.
*/
ListKeysPublisher keysPublisher = kmsAsyncClient.listKeysPaginator(listKeysRequest);
CompletableFuture<Void> future = keysPublisher
.subscribe(r -> r.keys().forEach(key ->
System.out.println("The key ARN is: " + key.keyArn() + ". The key Id is: " + key.keyId())))
.whenComplete((result, exception) -> {
if (exception != null) {
System.err.println("Error occurred: " + exception.getMessage());
} else {
System.out.println("Successfully listed all keys.");
}
});
try {
future.join();
} catch (Exception e) {
System.err.println("Failed to list keys: " + e.getMessage());
}
}
}
- PHP
-
- SDK for PHP
-
include "vendor/autoload.php";
use Aws\Kms\KmsClient;
echo "This file shows how to connect to the KmsClient, uses a paginator to get the keys for the account, and lists the KeyIds for up to 10 keys.\n";
$client = new KmsClient([]);
$pageLength = 10; // Change this value to change the number of records shown, or to break up the result into pages.
$keys = [];
$keysPaginator = $client->getPaginator("ListKeys", ['Limit' => $pageLength]);
foreach($keysPaginator as $page){
foreach($page['Keys'] as $index => $key){
echo "The $index index Key's ID is: {$key['KeyId']}\n";
}
echo "End of page one of results. Alter the \$pageLength variable to see more results.\n";
break;
}