Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.
Gunakan CreateDBClusterSnapshot
dengan AWS SDK atau CLI
Contoh kode berikut menunjukkan cara menggunakanCreateDBClusterSnapshot
.
Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:
- .NET
-
- AWS SDK for .NET
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. /// <summary> /// Create a snapshot of a cluster. /// </summary> /// <param name="dbClusterIdentifier">DB cluster identifier.</param> /// <param name="snapshotIdentifier">Identifier for the snapshot.</param> /// <returns>DB snapshot object.</returns> public async Task<DBClusterSnapshot> CreateClusterSnapshotByIdentifierAsync(string dbClusterIdentifier, string snapshotIdentifier) { var response = await _amazonRDS.CreateDBClusterSnapshotAsync( new CreateDBClusterSnapshotRequest() { DBClusterIdentifier = dbClusterIdentifier, DBClusterSnapshotIdentifier = snapshotIdentifier, }); return response.DBClusterSnapshot; }
-
Untuk API detailnya, lihat C reateDBCluster Snapshot di AWS SDK for .NET APIReferensi.
-
- C++
-
- SDKuntuk C ++
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::RDS::RDSClient client(clientConfig); Aws::RDS::Model::CreateDBClusterSnapshotRequest request; request.SetDBClusterIdentifier(DB_CLUSTER_IDENTIFIER); request.SetDBClusterSnapshotIdentifier(snapshotID); Aws::RDS::Model::CreateDBClusterSnapshotOutcome outcome = client.CreateDBClusterSnapshot(request); if (outcome.IsSuccess()) { std::cout << "Snapshot creation has started." << std::endl; } else { std::cerr << "Error with Aurora::CreateDBClusterSnapshot. " << outcome.GetError().GetMessage() << std::endl; cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, DB_CLUSTER_IDENTIFIER, DB_INSTANCE_IDENTIFIER, client); return false; }
-
Untuk API detailnya, lihat C reateDBCluster Snapshot di AWS SDK for C++ APIReferensi.
-
- Go
-
- SDKuntuk Go V2
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. type DbClusters struct { AuroraClient *rds.Client } // CreateClusterSnapshot creates a snapshot of a DB cluster. func (clusters *DbClusters) CreateClusterSnapshot(ctx context.Context, clusterName string, snapshotName string) ( *types.DBClusterSnapshot, error) { output, err := clusters.AuroraClient.CreateDBClusterSnapshot(ctx, &rds.CreateDBClusterSnapshotInput{ DBClusterIdentifier: aws.String(clusterName), DBClusterSnapshotIdentifier: aws.String(snapshotName), }) if err != nil { log.Printf("Couldn't create snapshot %v: %v\n", snapshotName, err) return nil, err } else { return output.DBClusterSnapshot, nil } }
-
Untuk API detailnya, lihat C reateDBCluster Snapshot
di AWS SDK for Go APIReferensi.
-
- Java
-
- SDKuntuk Java 2.x
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. public static void createDBClusterSnapshot(RdsClient rdsClient, String dbInstanceClusterIdentifier, String dbSnapshotIdentifier) { try { CreateDbClusterSnapshotRequest snapshotRequest = CreateDbClusterSnapshotRequest.builder() .dbClusterIdentifier(dbInstanceClusterIdentifier) .dbClusterSnapshotIdentifier(dbSnapshotIdentifier) .build(); CreateDbClusterSnapshotResponse response = rdsClient.createDBClusterSnapshot(snapshotRequest); System.out.println("The Snapshot ARN is " + response.dbClusterSnapshot().dbClusterSnapshotArn()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
-
Untuk API detailnya, lihat C reateDBCluster Snapshot di AWS SDK for Java 2.x APIReferensi.
-
- Kotlin
-
- SDKuntuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. suspend fun createDBClusterSnapshot( dbInstanceClusterIdentifier: String?, dbSnapshotIdentifier: String?, ) { val snapshotRequest = CreateDbClusterSnapshotRequest { dbClusterIdentifier = dbInstanceClusterIdentifier dbClusterSnapshotIdentifier = dbSnapshotIdentifier } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.createDbClusterSnapshot(snapshotRequest) println("The Snapshot ARN is ${response.dbClusterSnapshot?.dbClusterSnapshotArn}") } }
-
Untuk API detailnya, lihat C reateDBCluster Snapshot AWS
SDKuntuk referensi Kotlin API.
-
- Python
-
- SDKuntuk Python (Boto3)
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. class AuroraWrapper: """Encapsulates Aurora DB cluster actions.""" def __init__(self, rds_client): """ :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client. """ self.rds_client = rds_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ rds_client = boto3.client("rds") return cls(rds_client) def create_cluster_snapshot(self, snapshot_id, cluster_id): """ Creates a snapshot of a DB cluster. :param snapshot_id: The ID to give the created snapshot. :param cluster_id: The DB cluster to snapshot. :return: Data about the newly created snapshot. """ try: response = self.rds_client.create_db_cluster_snapshot( DBClusterSnapshotIdentifier=snapshot_id, DBClusterIdentifier=cluster_id ) snapshot = response["DBClusterSnapshot"] except ClientError as err: logger.error( "Couldn't create snapshot of %s. Here's why: %s: %s", cluster_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return snapshot
-
Untuk API detailnya, lihat C reateDBCluster Snapshot AWS SDKuntuk Referensi Python (APIBoto3).
-
- Rust
-
- SDKuntuk Rust
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. // Get a list of allowed engine versions. rds.DescribeDbEngineVersions(Engine='aurora-mysql', DBParameterGroupFamily=<the family used to create your parameter group in step 2>) // Create an Aurora DB cluster database cluster that contains a MySql database and uses the parameter group you created. // Wait for DB cluster to be ready. Call rds.DescribeDBClusters and check for Status == 'available'. // Get a list of instance classes available for the selected engine and engine version. rds.DescribeOrderableDbInstanceOptions(Engine='mysql', EngineVersion=). // Create a database instance in the cluster. // Wait for DB instance to be ready. Call rds.DescribeDbInstances and check for DBInstanceStatus == 'available'. pub async fn start_cluster_and_instance(&mut self) -> Result<(), ScenarioError> { if self.password.is_none() { return Err(ScenarioError::with( "Must set Secret Password before starting a cluster", )); } let create_db_cluster = self .rds .create_db_cluster( DB_CLUSTER_IDENTIFIER, DB_CLUSTER_PARAMETER_GROUP_NAME, DB_ENGINE, self.engine_version.as_deref().expect("engine version"), self.username.as_deref().expect("username"), self.password .replace(SecretString::new("".to_string())) .expect("password"), ) .await; if let Err(err) = create_db_cluster { return Err(ScenarioError::new( "Failed to create DB Cluster with cluster group", &err, )); } self.db_cluster_identifier = create_db_cluster .unwrap() .db_cluster .and_then(|c| c.db_cluster_identifier); if self.db_cluster_identifier.is_none() { return Err(ScenarioError::with("Created DB Cluster missing Identifier")); } info!( "Started a db cluster: {}", self.db_cluster_identifier .as_deref() .unwrap_or("Missing ARN") ); let create_db_instance = self .rds .create_db_instance( self.db_cluster_identifier.as_deref().expect("cluster name"), DB_INSTANCE_IDENTIFIER, self.instance_class.as_deref().expect("instance class"), DB_ENGINE, ) .await; if let Err(err) = create_db_instance { return Err(ScenarioError::new( "Failed to create Instance in DB Cluster", &err, )); } self.db_instance_identifier = create_db_instance .unwrap() .db_instance .and_then(|i| i.db_instance_identifier); // Cluster creation can take up to 20 minutes to become available let cluster_max_wait = Duration::from_secs(20 * 60); let waiter = Waiter::builder().max(cluster_max_wait).build(); while waiter.sleep().await.is_ok() { let cluster = self .rds .describe_db_clusters( self.db_cluster_identifier .as_deref() .expect("cluster identifier"), ) .await; if let Err(err) = cluster { warn!(?err, "Failed to describe cluster while waiting for ready"); continue; } let instance = self .rds .describe_db_instance( self.db_instance_identifier .as_deref() .expect("instance identifier"), ) .await; if let Err(err) = instance { return Err(ScenarioError::new( "Failed to find instance for cluster", &err, )); } let instances_available = instance .unwrap() .db_instances() .iter() .all(|instance| instance.db_instance_status() == Some("Available")); let endpoints = self .rds .describe_db_cluster_endpoints( self.db_cluster_identifier .as_deref() .expect("cluster identifier"), ) .await; if let Err(err) = endpoints { return Err(ScenarioError::new( "Failed to find endpoint for cluster", &err, )); } let endpoints_available = endpoints .unwrap() .db_cluster_endpoints() .iter() .all(|endpoint| endpoint.status() == Some("available")); if instances_available && endpoints_available { return Ok(()); } } Err(ScenarioError::with("timed out waiting for cluster")) } pub async fn snapshot_cluster( &self, db_cluster_identifier: &str, snapshot_name: &str, ) -> Result<CreateDbClusterSnapshotOutput, SdkError<CreateDBClusterSnapshotError>> { self.inner .create_db_cluster_snapshot() .db_cluster_identifier(db_cluster_identifier) .db_cluster_snapshot_identifier(snapshot_name) .send() .await } #[tokio::test] async fn test_start_cluster_and_instance() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_create_db_cluster() .withf(|id, params, engine, version, username, password| { assert_eq!(id, "RustSDKCodeExamplesDBCluster"); assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup"); assert_eq!(engine, "aurora-mysql"); assert_eq!(version, "aurora-mysql8.0"); assert_eq!(username, "test username"); assert_eq!(password.expose_secret(), "test password"); true }) .return_once(|id, _, _, _, _, _| { Ok(CreateDbClusterOutput::builder() .db_cluster(DbCluster::builder().db_cluster_identifier(id).build()) .build()) }); mock_rds .expect_create_db_instance() .withf(|cluster, name, class, engine| { assert_eq!(cluster, "RustSDKCodeExamplesDBCluster"); assert_eq!(name, "RustSDKCodeExamplesDBInstance"); assert_eq!(class, "m5.large"); assert_eq!(engine, "aurora-mysql"); true }) .return_once(|cluster, name, class, _| { Ok(CreateDbInstanceOutput::builder() .db_instance( DbInstance::builder() .db_cluster_identifier(cluster) .db_instance_identifier(name) .db_instance_class(class) .build(), ) .build()) }); mock_rds .expect_describe_db_clusters() .with(eq("RustSDKCodeExamplesDBCluster")) .return_once(|id| { Ok(DescribeDbClustersOutput::builder() .db_clusters(DbCluster::builder().db_cluster_identifier(id).build()) .build()) }); mock_rds .expect_describe_db_instance() .with(eq("RustSDKCodeExamplesDBInstance")) .return_once(|name| { Ok(DescribeDbInstancesOutput::builder() .db_instances( DbInstance::builder() .db_instance_identifier(name) .db_instance_status("Available") .build(), ) .build()) }); mock_rds .expect_describe_db_cluster_endpoints() .with(eq("RustSDKCodeExamplesDBCluster")) .return_once(|_| { Ok(DescribeDbClusterEndpointsOutput::builder() .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build()) .build()) }); let mut scenario = AuroraScenario::new(mock_rds); scenario.engine_version = Some("aurora-mysql8.0".into()); scenario.instance_class = Some("m5.large".into()); scenario.username = Some("test username".into()); scenario.password = Some(SecretString::new("test password".into())); tokio::time::pause(); let assertions = tokio::spawn(async move { let create = scenario.start_cluster_and_instance().await; assert!(create.is_ok()); assert!(scenario .password .replace(SecretString::new("BAD SECRET".into())) .unwrap() .expose_secret() .is_empty()); assert_eq!( scenario.db_cluster_identifier, Some("RustSDKCodeExamplesDBCluster".into()) ); }); tokio::time::advance(Duration::from_secs(1)).await; tokio::time::resume(); let _ = assertions.await; } #[tokio::test] async fn test_start_cluster_and_instance_cluster_create_error() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_create_db_cluster() .return_once(|_, _, _, _, _, _| { Err(SdkError::service_error( CreateDBClusterError::unhandled(Box::new(Error::new( ErrorKind::Other, "create db cluster error", ))), Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()), )) }); let mut scenario = AuroraScenario::new(mock_rds); scenario.engine_version = Some("aurora-mysql8.0".into()); scenario.instance_class = Some("m5.large".into()); scenario.username = Some("test username".into()); scenario.password = Some(SecretString::new("test password".into())); let create = scenario.start_cluster_and_instance().await; assert_matches!(create, Err(ScenarioError { message, context: _}) if message == "Failed to create DB Cluster with cluster group") } #[tokio::test] async fn test_start_cluster_and_instance_cluster_create_missing_id() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_create_db_cluster() .return_once(|_, _, _, _, _, _| { Ok(CreateDbClusterOutput::builder() .db_cluster(DbCluster::builder().build()) .build()) }); let mut scenario = AuroraScenario::new(mock_rds); scenario.engine_version = Some("aurora-mysql8.0".into()); scenario.instance_class = Some("m5.large".into()); scenario.username = Some("test username".into()); scenario.password = Some(SecretString::new("test password".into())); let create = scenario.start_cluster_and_instance().await; assert_matches!(create, Err(ScenarioError { message, context:_ }) if message == "Created DB Cluster missing Identifier"); } #[tokio::test] async fn test_start_cluster_and_instance_instance_create_error() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_create_db_cluster() .withf(|id, params, engine, version, username, password| { assert_eq!(id, "RustSDKCodeExamplesDBCluster"); assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup"); assert_eq!(engine, "aurora-mysql"); assert_eq!(version, "aurora-mysql8.0"); assert_eq!(username, "test username"); assert_eq!(password.expose_secret(), "test password"); true }) .return_once(|id, _, _, _, _, _| { Ok(CreateDbClusterOutput::builder() .db_cluster(DbCluster::builder().db_cluster_identifier(id).build()) .build()) }); mock_rds .expect_create_db_instance() .return_once(|_, _, _, _| { Err(SdkError::service_error( CreateDBInstanceError::unhandled(Box::new(Error::new( ErrorKind::Other, "create db instance error", ))), Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()), )) }); let mut scenario = AuroraScenario::new(mock_rds); scenario.engine_version = Some("aurora-mysql8.0".into()); scenario.instance_class = Some("m5.large".into()); scenario.username = Some("test username".into()); scenario.password = Some(SecretString::new("test password".into())); let create = scenario.start_cluster_and_instance().await; assert_matches!(create, Err(ScenarioError { message, context: _ }) if message == "Failed to create Instance in DB Cluster") } #[tokio::test] async fn test_start_cluster_and_instance_wait_hiccup() { let mut mock_rds = MockRdsImpl::default(); mock_rds .expect_create_db_cluster() .withf(|id, params, engine, version, username, password| { assert_eq!(id, "RustSDKCodeExamplesDBCluster"); assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup"); assert_eq!(engine, "aurora-mysql"); assert_eq!(version, "aurora-mysql8.0"); assert_eq!(username, "test username"); assert_eq!(password.expose_secret(), "test password"); true }) .return_once(|id, _, _, _, _, _| { Ok(CreateDbClusterOutput::builder() .db_cluster(DbCluster::builder().db_cluster_identifier(id).build()) .build()) }); mock_rds .expect_create_db_instance() .withf(|cluster, name, class, engine| { assert_eq!(cluster, "RustSDKCodeExamplesDBCluster"); assert_eq!(name, "RustSDKCodeExamplesDBInstance"); assert_eq!(class, "m5.large"); assert_eq!(engine, "aurora-mysql"); true }) .return_once(|cluster, name, class, _| { Ok(CreateDbInstanceOutput::builder() .db_instance( DbInstance::builder() .db_cluster_identifier(cluster) .db_instance_identifier(name) .db_instance_class(class) .build(), ) .build()) }); mock_rds .expect_describe_db_clusters() .with(eq("RustSDKCodeExamplesDBCluster")) .times(1) .returning(|_| { Err(SdkError::service_error( DescribeDBClustersError::unhandled(Box::new(Error::new( ErrorKind::Other, "describe cluster error", ))), Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()), )) }) .with(eq("RustSDKCodeExamplesDBCluster")) .times(1) .returning(|id| { Ok(DescribeDbClustersOutput::builder() .db_clusters(DbCluster::builder().db_cluster_identifier(id).build()) .build()) }); mock_rds.expect_describe_db_instance().return_once(|name| { Ok(DescribeDbInstancesOutput::builder() .db_instances( DbInstance::builder() .db_instance_identifier(name) .db_instance_status("Available") .build(), ) .build()) }); mock_rds .expect_describe_db_cluster_endpoints() .return_once(|_| { Ok(DescribeDbClusterEndpointsOutput::builder() .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build()) .build()) }); let mut scenario = AuroraScenario::new(mock_rds); scenario.engine_version = Some("aurora-mysql8.0".into()); scenario.instance_class = Some("m5.large".into()); scenario.username = Some("test username".into()); scenario.password = Some(SecretString::new("test password".into())); tokio::time::pause(); let assertions = tokio::spawn(async move { let create = scenario.start_cluster_and_instance().await; assert!(create.is_ok()); }); tokio::time::advance(Duration::from_secs(1)).await; tokio::time::advance(Duration::from_secs(1)).await; tokio::time::resume(); let _ = assertions.await; }
-
Untuk API detailnya, lihat C reateDBCluster Snapshot AWS
SDKuntuk API referensi Rust.
-
Untuk daftar lengkap panduan AWS SDK pengembang dan contoh kode, lihatMenggunakan layanan ini dengan AWS SDK. Topik ini juga mencakup informasi tentang memulai dan detail tentang SDK versi sebelumnya.