使用 Amazon SDK 的 Aurora 代码示例 - Amazon Aurora
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

使用 Amazon SDK 的 Aurora 代码示例

以下代码示例显示如何将 Aurora 与 Amazon 软件开发工具包(SDK)一起使用。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景是展示如何通过在同一服务中调用多个函数来完成特定任务任务的代码示例。

跨服务示例是指跨多个 Amazon Web Services工作的示例应用程序。

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将此服务与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

开始使用

以下代码示例显示如何开始使用 Aurora。

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

using Amazon.RDS; using Amazon.RDS.Model; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace AuroraActions; public static class HelloAurora { static async Task Main(string[] args) { // Use the AWS .NET Core Setup package to set up dependency injection for the // Amazon Relational Database Service (Amazon RDS). // Use your AWS profile name, or leave it blank to use the default profile. using var host = Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService<IAmazonRDS>() ).Build(); // Now the client is available for injection. Fetching it directly here for example purposes only. var rdsClient = host.Services.GetRequiredService<IAmazonRDS>(); // You can use await and any of the async methods to get a response. var response = await rdsClient.DescribeDBClustersAsync(new DescribeDBClustersRequest { IncludeShared = true }); Console.WriteLine($"Hello Amazon RDS Aurora! Let's list some clusters in this account:"); foreach (var cluster in response.DBClusters) { Console.WriteLine($"\tCluster: database: {cluster.DatabaseName} identifier: {cluster.DBClusterIdentifier}."); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 DescribeDBClusters

C++
适用于 C++ 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

CMakeLists.txt CMake 文件的代码。

# Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS rds) # Set this project's name. project("hello_aurora") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_aurora.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

hello_aurora.cpp 源文件的代码。

#include <aws/core/Aws.h> #include <aws/rds/RDSClient.h> #include <aws/rds/model/DescribeDBClustersRequest.h> #include <iostream> /* * A "Hello Aurora" starter application which initializes an Amazon Relational Database Service (Amazon RDS) client * and describes the Amazon Aurora (Aurora) clusters. * * main function * * Usage: 'hello_aurora' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. int result = 0; { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::RDS::RDSClient rdsClient(clientConfig); Aws::String marker; // Used for pagination. std::vector<Aws::String> clusterIds; do { Aws::RDS::Model::DescribeDBClustersRequest request; Aws::RDS::Model::DescribeDBClustersOutcome outcome = rdsClient.DescribeDBClusters(request); if (outcome.IsSuccess()) { for (auto &cluster: outcome.GetResult().GetDBClusters()) { clusterIds.push_back(cluster.GetDBClusterIdentifier()); } marker = outcome.GetResult().GetMarker(); } else { result = 1; std::cerr << "Error with Aurora::GDescribeDBClusters. " << outcome.GetError().GetMessage() << std::endl; break; } } while (!marker.empty()); std::cout << clusterIds.size() << " Aurora clusters found." << std::endl; for (auto &clusterId: clusterIds) { std::cout << " clusterId " << clusterId << std::endl; } } Aws::ShutdownAPI(options); // Should only be called once. return 0; }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 DescribeDBClusters

Go
适用于 Go V2 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/rds" ) // main uses the AWS SDK for Go V2 to create an Amazon Aurora client and list up to 20 // DB clusters in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { sdkConfig, err := config.LoadDefaultConfig(context.TODO()) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } auroraClient := rds.NewFromConfig(sdkConfig) const maxClusters = 20 fmt.Printf("Let's list up to %v DB clusters.\n", maxClusters) output, err := auroraClient.DescribeDBClusters(context.TODO(), &rds.DescribeDBClustersInput{MaxRecords: aws.Int32(maxClusters)}) if err != nil { fmt.Printf("Couldn't list DB clusters: %v\n", err) return } if len(output.DBClusters) == 0 { fmt.Println("No DB clusters found.") } else { for _, cluster := range output.DBClusters { fmt.Printf("DB cluster %v has database %v.\n", *cluster.DBClusterIdentifier, *cluster.DatabaseName) } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 DescribeDBClusters

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.paginators.DescribeDBClustersIterable; public class DescribeDbClusters { public static void main(String[] args) { Region region = Region.US_EAST_1; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); describeClusters(rdsClient); rdsClient.close(); } public static void describeClusters(RdsClient rdsClient) { DescribeDBClustersIterable clustersIterable = rdsClient.describeDBClustersPaginator(); clustersIterable.stream() .flatMap(r -> r.dbClusters().stream()) .forEach(cluster -> System.out .println("Database name: " + cluster.databaseName() + " Arn = " + cluster.dbClusterArn())); } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 DescribeDBClusters

Rust
适用于 Rust 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_sdk_rds::Client; #[derive(Debug)] struct Error(String); impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl std::error::Error for Error {} #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); let sdk_config = aws_config::from_env().load().await; let client = Client::new(&sdk_config); let describe_db_clusters_output = client .describe_db_clusters() .send() .await .map_err(|e| Error(e.to_string()))?; println!( "Found {} clusters:", describe_db_clusters_output.db_clusters().len() ); for cluster in describe_db_clusters_output.db_clusters() { let name = cluster.database_name().unwrap_or("Unknown"); let engine = cluster.engine().unwrap_or("Unknown"); let id = cluster.db_cluster_identifier().unwrap_or("Unknown"); let class = cluster.db_cluster_instance_class().unwrap_or("Unknown"); println!("\tDatabase: {name}",); println!("\t Engine: {engine}",); println!("\t ID: {id}",); println!("\tInstance: {class}",); } Ok(()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 DescribeDBClusters