D'autres AWS SDK exemples sont disponibles dans le GitHub dépôt AWS Doc SDK Examples
Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.
RDSExemples d'utilisation d'Amazon SDK pour Kotlin
Les exemples de code suivants vous montrent comment effectuer des actions et implémenter des scénarios courants en utilisant le AWS SDK pour Kotlin avec AmazonRDS.
Les principes de base sont des exemples de code qui vous montrent comment effectuer les opérations essentielles au sein d'un service.
Les actions sont des extraits de code de programmes plus larges et doivent être exécutées dans leur contexte. Alors que les actions vous montrent comment appeler des fonctions de service individuelles, vous pouvez les visualiser dans leur contexte dans leurs scénarios associés.
Les scénarios sont des exemples de code qui vous montrent comment accomplir des tâches spécifiques en appelant plusieurs fonctions au sein d'un service ou en les combinant à d'autres Services AWS.
Chaque exemple inclut un lien vers le code source complet, où vous trouverez des instructions sur la façon de configurer et d'exécuter le code en contexte.
Rubriques
Principes de base
L’exemple de code suivant illustre comment :
Créez un groupe de paramètres de bases de données personnalisé et définissez des valeurs pour les paramètres.
Créez une instance de base de données configurée pour utiliser le groupe de paramètres. L'instance de base de données contient également une base de données.
Prenez un instantané de l'instance.
Supprimez l'instance et le groupe de paramètres.
- SDKpour Kotlin
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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 } }
-
Pour API plus de détails, consultez les rubriques suivantes AWS SDKpour API référence à Kotlin.
-
Actions
L'exemple de code suivant montre comment utiliserCreateDBInstance
.
- SDKpour Kotlin
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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!") } }
-
Pour API plus de détails, voir C reateDBInstance
in AWS SDKpour la API référence à Kotlin.
-
L'exemple de code suivant montre comment utiliserDeleteDBInstance
.
- SDKpour Kotlin
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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}") } }
-
Pour API plus de détails, voir D eleteDBInstance
in AWS SDKpour la API référence à Kotlin.
-
L'exemple de code suivant montre comment utiliserDescribeAccountAttributes
.
- SDKpour Kotlin
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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}") } } }
-
Pour API plus de détails, voir DescribeAccountAttributes
la APIréférence AWS SDK à Kotlin.
-
L'exemple de code suivant montre comment utiliserDescribeDBInstances
.
- SDKpour Kotlin
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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}") } } }
-
Pour API plus de détails, voir D escribeDBInstances
in AWS SDKpour la API référence à Kotlin.
-
L'exemple de code suivant montre comment utiliserModifyDBInstance
.
- SDKpour Kotlin
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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}") } }
-
Pour API plus de détails, voir M odifyDBInstance
in AWS SDKpour une API référence à Kotlin.
-
Scénarios
L'exemple de code suivant montre comment créer une application Web qui suit les éléments de travail dans une base de données Amazon Aurora Serverless et utilise Amazon Simple Email Service (AmazonSES) pour envoyer des rapports.
- SDKpour Kotlin
-
Montre comment créer une application Web qui suit et génère des rapports sur les éléments de travail stockés dans une RDS base de données Amazon.
Pour obtenir le code source complet et les instructions sur la façon de configurer un Spring REST API qui interroge les données Amazon Aurora Serverless et pour une utilisation par une application React, consultez l'exemple complet sur GitHub
. Les services utilisés dans cet exemple
Aurora
Amazon RDS
Amazon RDS Data Service
Amazon SES