Amazon RDS 示例使SDK用科特林 - AWS SDK 程式碼範例

AWS 文檔 AWS SDK示例 GitHub 回購中有更多SDK示例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

Amazon RDS 示例使SDK用科特林

下列程式碼範例說明如何透過將 for Kotlin 與 Amazon 搭配使用來執行動作和實作常見案 AWS SDK例。RDS

基本概念是程式碼範例,會示範如何在服務中執行基本作業。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會顯示如何呼叫個別服務函數,但您可以在其相關案例中查看內容中的動作。

例是程式碼範例,向您展示如何透過呼叫服務中的多個函數或與其他函式結合來完成特定工作 AWS 服務。

每個範例都包含完整原始程式碼的連結,您可以在其中找到如何在內容中設定和執行程式碼的指示。

基本概念

以下程式碼範例顯示做法:

  • 建立自訂資料庫參數群組並設定參數值。

  • 建立資料庫執行個體,設定為使用參數群組。資料庫執行個體也包含資料庫。

  • 擷取執行個體的快照。

  • 刪除執行個體和參數群組。

SDK對於科特林
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/** Before running this 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-kotlin/latest/developer-guide/setup.html This example requires an AWS Secrets Manager secret that contains the database credentials. If you do not create a secret, this example will not work. For more details, see: https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html This example performs the following tasks: 1. Returns a list of the available DB engines by invoking the DescribeDbEngineVersions method. 2. Selects an engine family and create a custom DB parameter group by invoking the createDBParameterGroup method. 3. Gets the parameter groups by invoking the DescribeDbParameterGroups method. 4. Gets parameters in the group by invoking the DescribeDbParameters method. 5. Modifies both the auto_increment_offset and auto_increment_increment parameters by invoking the modifyDbParameterGroup method. 6. Gets and displays the updated parameters. 7. Gets a list of allowed engine versions by invoking the describeDbEngineVersions method. 8. Gets a list of micro instance classes available for the selected engine. 9. Creates an Amazon Relational Database Service (Amazon RDS) database instance that contains a MySQL database and uses the parameter group. 10. Waits for DB instance to be ready and prints out the connection endpoint value. 11. Creates a snapshot of the DB instance. 12. Waits for the DB snapshot to be ready. 13. Deletes the DB instance. 14. Deletes the parameter group. */ var sleepTime: Long = 20 suspend fun main(args: Array<String>) { val usage = """ Usage: <dbGroupName> <dbParameterGroupFamily> <dbInstanceIdentifier> <dbName> <dbSnapshotIdentifier><secretName> Where: dbGroupName - The database group name. dbParameterGroupFamily - The database parameter group name. dbInstanceIdentifier - The database instance identifier. dbName - The database name. dbSnapshotIdentifier - The snapshot identifier. secretName - The name of the AWS Secrets Manager secret that contains the database credentials. """ if (args.size != 6) { println(usage) exitProcess(1) } val dbGroupName = args[0] val dbParameterGroupFamily = args[1] val dbInstanceIdentifier = args[2] val dbName = args[3] val dbSnapshotIdentifier = args[4] val secretName = args[5] val gson = Gson() val user = gson.fromJson(getSecretValues(secretName).toString(), User::class.java) val username = user.username val userPassword = user.password println("1. Return a list of the available DB engines") describeDBEngines() println("2. Create a custom parameter group") createDBParameterGroup(dbGroupName, dbParameterGroupFamily) println("3. Get the parameter groups") describeDbParameterGroups(dbGroupName) println("4. Get the parameters in the group") describeDbParameters(dbGroupName, 0) println("5. Modify the auto_increment_offset parameter") modifyDBParas(dbGroupName) println("6. Display the updated value") describeDbParameters(dbGroupName, -1) println("7. Get a list of allowed engine versions") getAllowedEngines(dbParameterGroupFamily) println("8. Get a list of micro instance classes available for the selected engine") getMicroInstances() println("9. Create an RDS database instance that contains a MySql database and uses the parameter group") val dbARN = createDatabaseInstance(dbGroupName, dbInstanceIdentifier, dbName, username, userPassword) println("The ARN of the new database is $dbARN") println("10. Wait for DB instance to be ready") waitForDbInstanceReady(dbInstanceIdentifier) println("11. Create a snapshot of the DB instance") createDbSnapshot(dbInstanceIdentifier, dbSnapshotIdentifier) println("12. Wait for DB snapshot to be ready") waitForSnapshotReady(dbInstanceIdentifier, dbSnapshotIdentifier) println("13. Delete the DB instance") deleteDbInstance(dbInstanceIdentifier) println("14. Delete the parameter group") if (dbARN != null) { deleteParaGroup(dbGroupName, dbARN) } println("The Scenario has successfully completed.") } suspend fun deleteParaGroup( dbGroupName: String, dbARN: String, ) { var isDataDel = false var didFind: Boolean var instanceARN: String RdsClient { region = "us-west-2" }.use { rdsClient -> // Make sure that the database has been deleted. while (!isDataDel) { val response = rdsClient.describeDbInstances() val instanceList = response.dbInstances val listSize = instanceList?.size isDataDel = false // Reset this value. didFind = false // Reset this value. var index = 1 if (instanceList != null) { for (instance in instanceList) { instanceARN = instance.dbInstanceArn.toString() if (instanceARN.compareTo(dbARN) == 0) { println("$dbARN still exists") didFind = true } if (index == listSize && !didFind) { // Went through the entire list and did not find the database name. isDataDel = true } index++ } } } // Delete the para group. val parameterGroupRequest = DeleteDbParameterGroupRequest { dbParameterGroupName = dbGroupName } rdsClient.deleteDbParameterGroup(parameterGroupRequest) println("$dbGroupName was deleted.") } } suspend fun deleteDbInstance(dbInstanceIdentifierVal: String) { val deleteDbInstanceRequest = DeleteDbInstanceRequest { dbInstanceIdentifier = dbInstanceIdentifierVal deleteAutomatedBackups = true skipFinalSnapshot = true } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.deleteDbInstance(deleteDbInstanceRequest) print("The status of the database is ${response.dbInstance?.dbInstanceStatus}") } } // Waits until the snapshot instance is available. suspend fun waitForSnapshotReady( dbInstanceIdentifierVal: String?, dbSnapshotIdentifierVal: String?, ) { var snapshotReady = false var snapshotReadyStr: String println("Waiting for the snapshot to become available.") val snapshotsRequest = DescribeDbSnapshotsRequest { dbSnapshotIdentifier = dbSnapshotIdentifierVal dbInstanceIdentifier = dbInstanceIdentifierVal } while (!snapshotReady) { RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeDbSnapshots(snapshotsRequest) val snapshotList: List<DbSnapshot>? = response.dbSnapshots if (snapshotList != null) { for (snapshot in snapshotList) { snapshotReadyStr = snapshot.status.toString() if (snapshotReadyStr.contains("available")) { snapshotReady = true } else { print(".") delay(sleepTime * 1000) } } } } } println("The Snapshot is available!") } // Create an Amazon RDS snapshot. suspend fun createDbSnapshot( dbInstanceIdentifierVal: String?, dbSnapshotIdentifierVal: String?, ) { val snapshotRequest = CreateDbSnapshotRequest { dbInstanceIdentifier = dbInstanceIdentifierVal dbSnapshotIdentifier = dbSnapshotIdentifierVal } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.createDbSnapshot(snapshotRequest) print("The Snapshot id is ${response.dbSnapshot?.dbiResourceId}") } } // Waits until the database instance is available. suspend fun waitForDbInstanceReady(dbInstanceIdentifierVal: String?) { var instanceReady = false var instanceReadyStr: String println("Waiting for instance to become available.") val instanceRequest = DescribeDbInstancesRequest { dbInstanceIdentifier = dbInstanceIdentifierVal } var endpoint = "" while (!instanceReady) { RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeDbInstances(instanceRequest) val instanceList = response.dbInstances if (instanceList != null) { for (instance in instanceList) { instanceReadyStr = instance.dbInstanceStatus.toString() if (instanceReadyStr.contains("available")) { endpoint = instance.endpoint?.address.toString() instanceReady = true } else { print(".") delay(sleepTime * 1000) } } } } } println("Database instance is available! The connection endpoint is $endpoint") } // Create a database instance and return the ARN of the database. suspend fun createDatabaseInstance( dbGroupNameVal: String?, dbInstanceIdentifierVal: String?, dbNameVal: String?, masterUsernameVal: String?, masterUserPasswordVal: String?, ): String? { val instanceRequest = CreateDbInstanceRequest { dbInstanceIdentifier = dbInstanceIdentifierVal allocatedStorage = 100 dbName = dbNameVal dbParameterGroupName = dbGroupNameVal engine = "mysql" dbInstanceClass = "db.m4.large" engineVersion = "8.0" storageType = "standard" masterUsername = masterUsernameVal masterUserPassword = masterUserPasswordVal } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.createDbInstance(instanceRequest) print("The status is ${response.dbInstance?.dbInstanceStatus}") return response.dbInstance?.dbInstanceArn } } // Get a list of micro instances. suspend fun getMicroInstances() { val dbInstanceOptionsRequest = DescribeOrderableDbInstanceOptionsRequest { engine = "mysql" } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeOrderableDbInstanceOptions(dbInstanceOptionsRequest) val orderableDBInstances = response.orderableDbInstanceOptions if (orderableDBInstances != null) { for (dbInstanceOption in orderableDBInstances) { println("The engine version is ${dbInstanceOption.engineVersion}") println("The engine description is ${dbInstanceOption.engine}") } } } } // Get a list of allowed engine versions. suspend fun getAllowedEngines(dbParameterGroupFamilyVal: String?) { val versionsRequest = DescribeDbEngineVersionsRequest { dbParameterGroupFamily = dbParameterGroupFamilyVal engine = "mysql" } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeDbEngineVersions(versionsRequest) val dbEngines: List<DbEngineVersion>? = response.dbEngineVersions if (dbEngines != null) { for (dbEngine in dbEngines) { println("The engine version is ${dbEngine.engineVersion}") println("The engine description is ${dbEngine.dbEngineDescription}") } } } } // Modify the auto_increment_offset parameter. suspend fun modifyDBParas(dbGroupName: String) { val parameter1 = Parameter { parameterName = "auto_increment_offset" applyMethod = ApplyMethod.Immediate parameterValue = "5" } val paraList: ArrayList<Parameter> = ArrayList() paraList.add(parameter1) val groupRequest = ModifyDbParameterGroupRequest { dbParameterGroupName = dbGroupName parameters = paraList } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.modifyDbParameterGroup(groupRequest) println("The parameter group ${response.dbParameterGroupName} was successfully modified") } } // Retrieve parameters in the group. suspend fun describeDbParameters( dbGroupName: String?, flag: Int, ) { val dbParameterGroupsRequest: DescribeDbParametersRequest dbParameterGroupsRequest = if (flag == 0) { DescribeDbParametersRequest { dbParameterGroupName = dbGroupName } } else { DescribeDbParametersRequest { dbParameterGroupName = dbGroupName source = "user" } } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeDbParameters(dbParameterGroupsRequest) val dbParameters: List<Parameter>? = response.parameters var paraName: String if (dbParameters != null) { for (para in dbParameters) { // Only print out information about either auto_increment_offset or auto_increment_increment. paraName = para.parameterName.toString() if (paraName.compareTo("auto_increment_offset") == 0 || paraName.compareTo("auto_increment_increment ") == 0) { println("*** The parameter name is $paraName") System.out.println("*** The parameter value is ${para.parameterValue}") System.out.println("*** The parameter data type is ${para.dataType}") System.out.println("*** The parameter description is ${para.description}") System.out.println("*** The parameter allowed values is ${para.allowedValues}") } } } } } suspend fun describeDbParameterGroups(dbGroupName: String?) { val groupsRequest = DescribeDbParameterGroupsRequest { dbParameterGroupName = dbGroupName maxRecords = 20 } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeDbParameterGroups(groupsRequest) val groups = response.dbParameterGroups if (groups != null) { for (group in groups) { println("The group name is ${group.dbParameterGroupName}") println("The group description is ${group.description}") } } } } // Create a parameter group. suspend fun createDBParameterGroup( dbGroupName: String?, dbParameterGroupFamilyVal: String?, ) { val groupRequest = CreateDbParameterGroupRequest { dbParameterGroupName = dbGroupName dbParameterGroupFamily = dbParameterGroupFamilyVal description = "Created by using the AWS SDK for Kotlin" } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.createDbParameterGroup(groupRequest) println("The group name is ${response.dbParameterGroup?.dbParameterGroupName}") } } // Returns a list of the available DB engines. suspend fun describeDBEngines() { val engineVersionsRequest = DescribeDbEngineVersionsRequest { defaultOnly = true engine = "mysql" maxRecords = 20 } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeDbEngineVersions(engineVersionsRequest) val engines: List<DbEngineVersion>? = response.dbEngineVersions // Get all DbEngineVersion objects. if (engines != null) { for (engineOb in engines) { println("The name of the DB parameter group family for the database engine is ${engineOb.dbParameterGroupFamily}.") println("The name of the database engine ${engineOb.engine}.") println("The version number of the database engine ${engineOb.engineVersion}") } } } } suspend fun getSecretValues(secretName: String?): String? { val valueRequest = GetSecretValueRequest { secretId = secretName } SecretsManagerClient { region = "us-west-2" }.use { secretsClient -> val valueResponse = secretsClient.getSecretValue(valueRequest) return valueResponse.secretString } }

動作

下列程式碼範例會示範如何使用CreateDBInstance

SDK對於科特林
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun createDatabaseInstance( dbInstanceIdentifierVal: String?, dbNamedbVal: String?, masterUsernameVal: String?, masterUserPasswordVal: String?, ) { val instanceRequest = CreateDbInstanceRequest { dbInstanceIdentifier = dbInstanceIdentifierVal allocatedStorage = 100 dbName = dbNamedbVal engine = "mysql" dbInstanceClass = "db.m4.large" engineVersion = "8.0" storageType = "standard" masterUsername = masterUsernameVal masterUserPassword = masterUserPasswordVal } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.createDbInstance(instanceRequest) print("The status is ${response.dbInstance?.dbInstanceStatus}") } } // Waits until the database instance is available. suspend fun waitForInstanceReady(dbInstanceIdentifierVal: String?) { val sleepTime: Long = 20 var instanceReady = false var instanceReadyStr: String println("Waiting for instance to become available.") val instanceRequest = DescribeDbInstancesRequest { dbInstanceIdentifier = dbInstanceIdentifierVal } RdsClient { region = "us-west-2" }.use { rdsClient -> while (!instanceReady) { val response = rdsClient.describeDbInstances(instanceRequest) val instanceList = response.dbInstances if (instanceList != null) { for (instance in instanceList) { instanceReadyStr = instance.dbInstanceStatus.toString() if (instanceReadyStr.contains("available")) { instanceReady = true } else { println("...$instanceReadyStr") delay(sleepTime * 1000) } } } } println("Database instance is available!") } }
  • 有API關詳細信息,請參閱reateDBInstance中AWS SDK的 C 以獲取 Kotlin API 的參考。

下列程式碼範例會示範如何使用DeleteDBInstance

SDK對於科特林
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun deleteDatabaseInstance(dbInstanceIdentifierVal: String?) { val deleteDbInstanceRequest = DeleteDbInstanceRequest { dbInstanceIdentifier = dbInstanceIdentifierVal deleteAutomatedBackups = true skipFinalSnapshot = true } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.deleteDbInstance(deleteDbInstanceRequest) print("The status of the database is ${response.dbInstance?.dbInstanceStatus}") } }
  • 有API關詳細信息,請參閱eleteDBInstance中AWS SDK的 D 以獲取 Kotlin API 的參考。

下列程式碼範例會示範如何使用DescribeAccountAttributes

SDK對於科特林
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun getAccountAttributes() { RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeAccountAttributes(DescribeAccountAttributesRequest {}) response.accountQuotas?.forEach { quotas -> val response = response.accountQuotas println("Name is: ${quotas.accountQuotaName}") println("Max value is ${quotas.max}") } } }

下列程式碼範例會示範如何使用DescribeDBInstances

SDK對於科特林
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun describeInstances() { RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeDbInstances(DescribeDbInstancesRequest {}) response.dbInstances?.forEach { instance -> println("Instance Identifier is ${instance.dbInstanceIdentifier}") println("The Engine is ${instance.engine}") println("Connection endpoint is ${instance.endpoint?.address}") } } }
  • 有API關詳細信息,請參閱escribeDBInstances中AWS SDK的 D 以獲取 Kotlin API 的參考。

下列程式碼範例會示範如何使用ModifyDBInstance

SDK對於科特林
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun updateIntance( dbInstanceIdentifierVal: String?, masterUserPasswordVal: String?, ) { val request = ModifyDbInstanceRequest { dbInstanceIdentifier = dbInstanceIdentifierVal publiclyAccessible = true masterUserPassword = masterUserPasswordVal } RdsClient { region = "us-west-2" }.use { rdsClient -> val instanceResponse = rdsClient.modifyDbInstance(request) println("The ARN of the modified database is ${instanceResponse.dbInstance?.dbInstanceArn}") } }
  • 有API關詳細信息,請參見 M odifyDBInstanceAWS SDK的 Kotlin API 參考。

案例

下列程式碼範例示範如何建立可追蹤 Amazon Aurora 無伺服器資料庫中工作項目的 Web 應用程式,並使用 Amazon 簡單電子郵件服務 (AmazonSES) 傳送報告。

SDK對於科特林

示範如何建立 Web 應用程式,以追蹤和報告 Amazon RDS 資料庫中存放的工作項目。

有關如何設置查詢 Amazon Aurora 無服務器數據以及供 React 應RESTAPI用程序使用的 Spring 的完整源代碼和說明,請參閱上GitHub的完整示例。

此範例中使用的服務
  • Aurora

  • Amazon RDS

  • Amazon RDS 數據服務

  • Amazon SES