기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
Java 2.xSDK용 를 사용하는 Amazon RDS 예제
다음 코드 예제에서는 Amazon 에서 를 사용하여 작업을 수행하고 일반적인 시나리오 AWS SDK for Java 2.x 를 구현하는 방법을 보여줍니다RDS.
기본 사항은 서비스 내에서 필수 작업을 수행하는 방법을 보여주는 코드 예제입니다.
작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 직접적으로 호출하는 방법을 보여주며 관련 시나리오의 컨텍스트에 맞는 작업을 볼 수 있습니다.
시나리오는 동일한 서비스 내에서 또는 다른 AWS 서비스와 결합된 상태에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예제입니다.
각 예제에는 컨텍스트에서 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 전체 소스 코드에 대한 링크가 포함되어 있습니다.
시작하기
다음 코드 예제에서는 Amazon 를 시작하는 방법을 보여줍니다RDS.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse; import software.amazon.awssdk.services.rds.model.DBInstance; import software.amazon.awssdk.services.rds.model.RdsException; import java.util.List; /** * 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 DescribeDBInstances { public static void main(String[] args) { Region region = Region.US_EAST_1; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); describeInstances(rdsClient); rdsClient.close(); } public static void describeInstances(RdsClient rdsClient) { try { DescribeDbInstancesResponse response = rdsClient.describeDBInstances(); List<DBInstance> instanceList = response.dbInstances(); for (DBInstance instance : instanceList) { System.out.println("Instance ARN is: " + instance.dbInstanceArn()); System.out.println("The Engine is " + instance.engine()); System.out.println("Connection endpoint is" + instance.endpoint().address()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } }
-
API 자세한 내용은 AWS SDK for Java 2.x API 참조의 DescribeDBInstances를 참조하세요.
-
기본 사항
다음 코드 예시는 다음과 같은 작업을 수행하는 방법을 보여줍니다.
사용자 지정 DB 파라미터 그룹을 생성하고 파라미터 값을 설정합니다.
파라미터 그룹을 사용하도록 구성된 DB 인스턴스를 생성합니다. DB 인스턴스에는 데이터베이스도 포함되어 있습니다.
인스턴스의 스냅샷을 만듭니다.
인스턴스 및 파라미터 그룹을 삭제합니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. 여러 작업을 실행합니다.
import com.google.gson.Gson; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.CreateDbInstanceRequest; import software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse; import software.amazon.awssdk.services.rds.model.CreateDbParameterGroupResponse; import software.amazon.awssdk.services.rds.model.CreateDbSnapshotRequest; import software.amazon.awssdk.services.rds.model.CreateDbSnapshotResponse; import software.amazon.awssdk.services.rds.model.DBEngineVersion; import software.amazon.awssdk.services.rds.model.DBInstance; import software.amazon.awssdk.services.rds.model.DBParameterGroup; import software.amazon.awssdk.services.rds.model.DBSnapshot; import software.amazon.awssdk.services.rds.model.DeleteDbInstanceRequest; import software.amazon.awssdk.services.rds.model.DeleteDbInstanceResponse; import software.amazon.awssdk.services.rds.model.DescribeDbEngineVersionsRequest; import software.amazon.awssdk.services.rds.model.DescribeDbEngineVersionsResponse; import software.amazon.awssdk.services.rds.model.DescribeDbInstancesRequest; import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse; import software.amazon.awssdk.services.rds.model.DescribeDbParameterGroupsResponse; import software.amazon.awssdk.services.rds.model.DescribeDbParametersResponse; import software.amazon.awssdk.services.rds.model.DescribeDbSnapshotsRequest; import software.amazon.awssdk.services.rds.model.DescribeDbSnapshotsResponse; import software.amazon.awssdk.services.rds.model.DescribeOrderableDbInstanceOptionsResponse; import software.amazon.awssdk.services.rds.model.ModifyDbParameterGroupResponse; import software.amazon.awssdk.services.rds.model.OrderableDBInstanceOption; import software.amazon.awssdk.services.rds.model.Parameter; import software.amazon.awssdk.services.rds.model.RdsException; import software.amazon.awssdk.services.rds.model.CreateDbParameterGroupRequest; import software.amazon.awssdk.services.rds.model.DescribeDbParameterGroupsRequest; import software.amazon.awssdk.services.rds.model.DescribeDbParametersRequest; import software.amazon.awssdk.services.rds.model.ModifyDbParameterGroupRequest; import software.amazon.awssdk.services.rds.model.DescribeOrderableDbInstanceOptionsRequest; import software.amazon.awssdk.services.rds.model.DeleteDbParameterGroupRequest; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; import java.util.ArrayList; import java.util.List; /** * 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 * * 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 details, see: * * https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html * * This Java example performs these tasks: * * 1. Returns a list of the available DB engines. * 2. Selects an engine family and create a custom DB parameter group. * 3. Gets the parameter groups. * 4. Gets parameters in the group. * 5. Modifies the auto_increment_offset parameter. * 6. Gets and displays the updated parameters. * 7. Gets a list of allowed engine versions. * 8. Gets a list of micro instance classes available for the selected engine. * 9. Creates an RDS database instance that contains a MySql database and uses * the parameter group. * 10. Waits for the DB instance to be ready and prints out the connection * endpoint value. * 11. Creates a snapshot of the DB instance. * 12. Waits for an RDS DB snapshot to be ready. * 13. Deletes the RDS DB instance. * 14. Deletes the parameter group. */ public class RDSScenario { public static long sleepTime = 20; public static final String DASHES = new String(new char[80]).replace("\0", "-"); public static void main(String[] args) throws InterruptedException { final String usage = """ Usage: <dbGroupName> <dbParameterGroupFamily> <dbInstanceIdentifier> <dbName> <dbSnapshotIdentifier> <secretName> Where: dbGroupName - The database group name.\s dbParameterGroupFamily - The database parameter group name (for example, mysql8.0). dbInstanceIdentifier - The database instance identifier\s dbName - The database name.\s dbSnapshotIdentifier - The snapshot identifier.\s secretName - The name of the AWS Secrets Manager secret that contains the database credentials" """; if (args.length != 6) { System.out.println(usage); System.exit(1); } String dbGroupName = args[0]; String dbParameterGroupFamily = args[1]; String dbInstanceIdentifier = args[2]; String dbName = args[3]; String dbSnapshotIdentifier = args[4]; String secretName = args[5]; Gson gson = new Gson(); User user = gson.fromJson(String.valueOf(getSecretValues(secretName)), User.class); String masterUsername = user.getUsername(); String masterUserPassword = user.getPassword(); Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon RDS example scenario."); System.out.println(DASHES); System.out.println(DASHES); System.out.println("1. Return a list of the available DB engines"); describeDBEngines(rdsClient); System.out.println(DASHES); System.out.println(DASHES); System.out.println("2. Create a custom parameter group"); createDBParameterGroup(rdsClient, dbGroupName, dbParameterGroupFamily); System.out.println(DASHES); System.out.println(DASHES); System.out.println("3. Get the parameter group"); describeDbParameterGroups(rdsClient, dbGroupName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("4. Get the parameters in the group"); describeDbParameters(rdsClient, dbGroupName, 0); System.out.println(DASHES); System.out.println(DASHES); System.out.println("5. Modify the auto_increment_offset parameter"); modifyDBParas(rdsClient, dbGroupName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("6. Display the updated value"); describeDbParameters(rdsClient, dbGroupName, -1); System.out.println(DASHES); System.out.println(DASHES); System.out.println("7. Get a list of allowed engine versions"); getAllowedEngines(rdsClient, dbParameterGroupFamily); System.out.println(DASHES); System.out.println(DASHES); System.out.println("8. Get a list of micro instance classes available for the selected engine"); getMicroInstances(rdsClient); System.out.println(DASHES); System.out.println(DASHES); System.out.println( "9. Create an RDS database instance that contains a MySql database and uses the parameter group"); String dbARN = createDatabaseInstance(rdsClient, dbGroupName, dbInstanceIdentifier, dbName, masterUsername, masterUserPassword); System.out.println("The ARN of the new database is " + dbARN); System.out.println(DASHES); System.out.println(DASHES); System.out.println("10. Wait for DB instance to be ready"); waitForInstanceReady(rdsClient, dbInstanceIdentifier); System.out.println(DASHES); System.out.println(DASHES); System.out.println("11. Create a snapshot of the DB instance"); createSnapshot(rdsClient, dbInstanceIdentifier, dbSnapshotIdentifier); System.out.println(DASHES); System.out.println(DASHES); System.out.println("12. Wait for DB snapshot to be ready"); waitForSnapshotReady(rdsClient, dbInstanceIdentifier, dbSnapshotIdentifier); System.out.println(DASHES); System.out.println(DASHES); System.out.println("13. Delete the DB instance"); deleteDatabaseInstance(rdsClient, dbInstanceIdentifier); System.out.println(DASHES); System.out.println(DASHES); System.out.println("14. Delete the parameter group"); deleteParaGroup(rdsClient, dbGroupName, dbARN); System.out.println(DASHES); System.out.println(DASHES); System.out.println("The Scenario has successfully completed."); System.out.println(DASHES); rdsClient.close(); } private static SecretsManagerClient getSecretClient() { Region region = Region.US_WEST_2; return SecretsManagerClient.builder() .region(region) .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } public static String getSecretValues(String secretName) { SecretsManagerClient secretClient = getSecretClient(); GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() .secretId(secretName) .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); } // Delete the parameter group after database has been deleted. // An exception is thrown if you attempt to delete the para group while database // exists. public static void deleteParaGroup(RdsClient rdsClient, String dbGroupName, String dbARN) throws InterruptedException { try { boolean isDataDel = false; boolean didFind; String instanceARN; // Make sure that the database has been deleted. while (!isDataDel) { DescribeDbInstancesResponse response = rdsClient.describeDBInstances(); List<DBInstance> instanceList = response.dbInstances(); int listSize = instanceList.size(); didFind = false; int index = 1; for (DBInstance instance : instanceList) { instanceARN = instance.dbInstanceArn(); if (instanceARN.compareTo(dbARN) == 0) { System.out.println(dbARN + " still exists"); didFind = true; } if ((index == listSize) && (!didFind)) { // Went through the entire list and did not find the database ARN. isDataDel = true; } Thread.sleep(sleepTime * 1000); index++; } } // Delete the para group. DeleteDbParameterGroupRequest parameterGroupRequest = DeleteDbParameterGroupRequest.builder() .dbParameterGroupName(dbGroupName) .build(); rdsClient.deleteDBParameterGroup(parameterGroupRequest); System.out.println(dbGroupName + " was deleted."); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } // Delete the DB instance. public static void deleteDatabaseInstance(RdsClient rdsClient, String dbInstanceIdentifier) { try { DeleteDbInstanceRequest deleteDbInstanceRequest = DeleteDbInstanceRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .deleteAutomatedBackups(true) .skipFinalSnapshot(true) .build(); DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(deleteDbInstanceRequest); System.out.print("The status of the database is " + response.dbInstance().dbInstanceStatus()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } // Waits until the snapshot instance is available. public static void waitForSnapshotReady(RdsClient rdsClient, String dbInstanceIdentifier, String dbSnapshotIdentifier) { try { boolean snapshotReady = false; String snapshotReadyStr; System.out.println("Waiting for the snapshot to become available."); DescribeDbSnapshotsRequest snapshotsRequest = DescribeDbSnapshotsRequest.builder() .dbSnapshotIdentifier(dbSnapshotIdentifier) .dbInstanceIdentifier(dbInstanceIdentifier) .build(); while (!snapshotReady) { DescribeDbSnapshotsResponse response = rdsClient.describeDBSnapshots(snapshotsRequest); List<DBSnapshot> snapshotList = response.dbSnapshots(); for (DBSnapshot snapshot : snapshotList) { snapshotReadyStr = snapshot.status(); if (snapshotReadyStr.contains("available")) { snapshotReady = true; } else { System.out.print("."); Thread.sleep(sleepTime * 1000); } } } System.out.println("The Snapshot is available!"); } catch (RdsException | InterruptedException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } // Create an Amazon RDS snapshot. public static void createSnapshot(RdsClient rdsClient, String dbInstanceIdentifier, String dbSnapshotIdentifier) { try { CreateDbSnapshotRequest snapshotRequest = CreateDbSnapshotRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .dbSnapshotIdentifier(dbSnapshotIdentifier) .build(); CreateDbSnapshotResponse response = rdsClient.createDBSnapshot(snapshotRequest); System.out.println("The Snapshot id is " + response.dbSnapshot().dbiResourceId()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } // Waits until the database instance is available. public static void waitForInstanceReady(RdsClient rdsClient, String dbInstanceIdentifier) { boolean instanceReady = false; String instanceReadyStr; System.out.println("Waiting for instance to become available."); try { DescribeDbInstancesRequest instanceRequest = DescribeDbInstancesRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .build(); String endpoint = ""; while (!instanceReady) { DescribeDbInstancesResponse response = rdsClient.describeDBInstances(instanceRequest); List<DBInstance> instanceList = response.dbInstances(); for (DBInstance instance : instanceList) { instanceReadyStr = instance.dbInstanceStatus(); if (instanceReadyStr.contains("available")) { endpoint = instance.endpoint().address(); instanceReady = true; } else { System.out.print("."); Thread.sleep(sleepTime * 1000); } } } System.out.println("Database instance is available! The connection endpoint is " + endpoint); } catch (RdsException | InterruptedException e) { System.err.println(e.getMessage()); System.exit(1); } } // Create a database instance and return the ARN of the database. public static String createDatabaseInstance(RdsClient rdsClient, String dbGroupName, String dbInstanceIdentifier, String dbName, String masterUsername, String masterUserPassword) { try { CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .allocatedStorage(100) .dbName(dbName) .dbParameterGroupName(dbGroupName) .engine("mysql") .dbInstanceClass("db.m4.large") .engineVersion("8.0") .storageType("standard") .masterUsername(masterUsername) .masterUserPassword(masterUserPassword) .build(); CreateDbInstanceResponse response = rdsClient.createDBInstance(instanceRequest); System.out.print("The status is " + response.dbInstance().dbInstanceStatus()); return response.dbInstance().dbInstanceArn(); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } return ""; } // Get a list of micro instances. public static void getMicroInstances(RdsClient rdsClient) { try { DescribeOrderableDbInstanceOptionsRequest dbInstanceOptionsRequest = DescribeOrderableDbInstanceOptionsRequest .builder() .engine("mysql") .build(); DescribeOrderableDbInstanceOptionsResponse response = rdsClient .describeOrderableDBInstanceOptions(dbInstanceOptionsRequest); List<OrderableDBInstanceOption> orderableDBInstances = response.orderableDBInstanceOptions(); for (OrderableDBInstanceOption dbInstanceOption : orderableDBInstances) { System.out.println("The engine version is " + dbInstanceOption.engineVersion()); System.out.println("The engine description is " + dbInstanceOption.engine()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } // Get a list of allowed engine versions. public static void getAllowedEngines(RdsClient rdsClient, String dbParameterGroupFamily) { try { DescribeDbEngineVersionsRequest versionsRequest = DescribeDbEngineVersionsRequest.builder() .dbParameterGroupFamily(dbParameterGroupFamily) .engine("mysql") .build(); DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(versionsRequest); List<DBEngineVersion> dbEngines = response.dbEngineVersions(); for (DBEngineVersion dbEngine : dbEngines) { System.out.println("The engine version is " + dbEngine.engineVersion()); System.out.println("The engine description is " + dbEngine.dbEngineDescription()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } // Modify auto_increment_offset and auto_increment_increment parameters. public static void modifyDBParas(RdsClient rdsClient, String dbGroupName) { try { Parameter parameter1 = Parameter.builder() .parameterName("auto_increment_offset") .applyMethod("immediate") .parameterValue("5") .build(); List<Parameter> paraList = new ArrayList<>(); paraList.add(parameter1); ModifyDbParameterGroupRequest groupRequest = ModifyDbParameterGroupRequest.builder() .dbParameterGroupName(dbGroupName) .parameters(paraList) .build(); ModifyDbParameterGroupResponse response = rdsClient.modifyDBParameterGroup(groupRequest); System.out.println("The parameter group " + response.dbParameterGroupName() + " was successfully modified"); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } // Retrieve parameters in the group. public static void describeDbParameters(RdsClient rdsClient, String dbGroupName, int flag) { try { DescribeDbParametersRequest dbParameterGroupsRequest; if (flag == 0) { dbParameterGroupsRequest = DescribeDbParametersRequest.builder() .dbParameterGroupName(dbGroupName) .build(); } else { dbParameterGroupsRequest = DescribeDbParametersRequest.builder() .dbParameterGroupName(dbGroupName) .source("user") .build(); } DescribeDbParametersResponse response = rdsClient.describeDBParameters(dbParameterGroupsRequest); List<Parameter> dbParameters = response.parameters(); String paraName; for (Parameter para : dbParameters) { // Only print out information about either auto_increment_offset or // auto_increment_increment. paraName = para.parameterName(); if ((paraName.compareTo("auto_increment_offset") == 0) || (paraName.compareTo("auto_increment_increment ") == 0)) { System.out.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()); } } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } public static void describeDbParameterGroups(RdsClient rdsClient, String dbGroupName) { try { DescribeDbParameterGroupsRequest groupsRequest = DescribeDbParameterGroupsRequest.builder() .dbParameterGroupName(dbGroupName) .maxRecords(20) .build(); DescribeDbParameterGroupsResponse response = rdsClient.describeDBParameterGroups(groupsRequest); List<DBParameterGroup> groups = response.dbParameterGroups(); for (DBParameterGroup group : groups) { System.out.println("The group name is " + group.dbParameterGroupName()); System.out.println("The group description is " + group.description()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } public static void createDBParameterGroup(RdsClient rdsClient, String dbGroupName, String dbParameterGroupFamily) { try { CreateDbParameterGroupRequest groupRequest = CreateDbParameterGroupRequest.builder() .dbParameterGroupName(dbGroupName) .dbParameterGroupFamily(dbParameterGroupFamily) .description("Created by using the AWS SDK for Java") .build(); CreateDbParameterGroupResponse response = rdsClient.createDBParameterGroup(groupRequest); System.out.println("The group name is " + response.dbParameterGroup().dbParameterGroupName()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } public static void describeDBEngines(RdsClient rdsClient) { try { DescribeDbEngineVersionsRequest engineVersionsRequest = DescribeDbEngineVersionsRequest.builder() .defaultOnly(true) .engine("mysql") .maxRecords(20) .build(); DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(engineVersionsRequest); List<DBEngineVersion> engines = response.dbEngineVersions(); // Get all DBEngineVersion objects. for (DBEngineVersion engineOb : engines) { System.out.println("The name of the DB parameter group family for the database engine is " + engineOb.dbParameterGroupFamily()); System.out.println("The name of the database engine " + engineOb.engine()); System.out.println("The version number of the database engine " + engineOb.engineVersion()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } }
작업
다음 코드 예시에서는 CreateDBInstance
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. import com.google.gson.Gson; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.DescribeDbInstancesRequest; import software.amazon.awssdk.services.rds.model.CreateDbInstanceRequest; import software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse; import software.amazon.awssdk.services.rds.model.RdsException; import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse; import software.amazon.awssdk.services.rds.model.DBInstance; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; import java.util.List; /** * 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 * * 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 * * */ public class CreateDBInstance { public static long sleepTime = 20; public static void main(String[] args) { final String usage = """ Usage: <dbInstanceIdentifier> <dbName> <secretName> Where: dbInstanceIdentifier - The database instance identifier.\s dbName - The database name.\s secretName - The name of the AWS Secrets Manager secret that contains the database credentials." """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String dbInstanceIdentifier = args[0]; String dbName = args[1]; String secretName = args[2]; Gson gson = new Gson(); User user = gson.fromJson(String.valueOf(getSecretValues(secretName)), User.class); Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); createDatabaseInstance(rdsClient, dbInstanceIdentifier, dbName, user.getUsername(), user.getPassword()); waitForInstanceReady(rdsClient, dbInstanceIdentifier); rdsClient.close(); } private static SecretsManagerClient getSecretClient() { Region region = Region.US_WEST_2; return SecretsManagerClient.builder() .region(region) .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } private static String getSecretValues(String secretName) { SecretsManagerClient secretClient = getSecretClient(); GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() .secretId(secretName) .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); } public static void createDatabaseInstance(RdsClient rdsClient, String dbInstanceIdentifier, String dbName, String userName, String userPassword) { try { CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .allocatedStorage(100) .dbName(dbName) .engine("mysql") .dbInstanceClass("db.m4.large") .engineVersion("8.0") .storageType("standard") .masterUsername(userName) .masterUserPassword(userPassword) .build(); CreateDbInstanceResponse response = rdsClient.createDBInstance(instanceRequest); System.out.print("The status is " + response.dbInstance().dbInstanceStatus()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } // Waits until the database instance is available. public static void waitForInstanceReady(RdsClient rdsClient, String dbInstanceIdentifier) { boolean instanceReady = false; String instanceReadyStr; System.out.println("Waiting for instance to become available."); try { DescribeDbInstancesRequest instanceRequest = DescribeDbInstancesRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .build(); // Loop until the cluster is ready. while (!instanceReady) { DescribeDbInstancesResponse response = rdsClient.describeDBInstances(instanceRequest); List<DBInstance> instanceList = response.dbInstances(); for (DBInstance instance : instanceList) { instanceReadyStr = instance.dbInstanceStatus(); if (instanceReadyStr.contains("available")) instanceReady = true; else { System.out.print("."); Thread.sleep(sleepTime * 1000); } } } System.out.println("Database instance is available!"); } catch (RdsException | InterruptedException e) { System.err.println(e.getMessage()); System.exit(1); } }
-
API 자세한 내용은 AWS SDK for Java 2.x API 참조의 CreateDBInstance를 참조하세요.
-
다음 코드 예시에서는 CreateDBParameterGroup
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. public static void createDBParameterGroup(RdsClient rdsClient, String dbGroupName, String dbParameterGroupFamily) { try { CreateDbParameterGroupRequest groupRequest = CreateDbParameterGroupRequest.builder() .dbParameterGroupName(dbGroupName) .dbParameterGroupFamily(dbParameterGroupFamily) .description("Created by using the AWS SDK for Java") .build(); CreateDbParameterGroupResponse response = rdsClient.createDBParameterGroup(groupRequest); System.out.println("The group name is " + response.dbParameterGroup().dbParameterGroupName()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
-
API 자세한 내용은 참조의 C reateDBParameter그룹을 참조하세요. AWS SDK for Java 2.x API
-
다음 코드 예시에서는 CreateDBSnapshot
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. // Create an Amazon RDS snapshot. public static void createSnapshot(RdsClient rdsClient, String dbInstanceIdentifier, String dbSnapshotIdentifier) { try { CreateDbSnapshotRequest snapshotRequest = CreateDbSnapshotRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .dbSnapshotIdentifier(dbSnapshotIdentifier) .build(); CreateDbSnapshotResponse response = rdsClient.createDBSnapshot(snapshotRequest); System.out.println("The Snapshot id is " + response.dbSnapshot().dbiResourceId()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
-
API 자세한 내용은 AWS SDK for Java 2.x API 참조의 CreateDBSnapshot를 참조하세요.
-
다음 코드 예시에서는 DeleteDBInstance
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.DeleteDbInstanceRequest; import software.amazon.awssdk.services.rds.model.DeleteDbInstanceResponse; import software.amazon.awssdk.services.rds.model.RdsException; /** * 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 DeleteDBInstance { public static void main(String[] args) { final String usage = """ Usage: <dbInstanceIdentifier>\s Where: dbInstanceIdentifier - The database instance identifier\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String dbInstanceIdentifier = args[0]; Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); deleteDatabaseInstance(rdsClient, dbInstanceIdentifier); rdsClient.close(); } public static void deleteDatabaseInstance(RdsClient rdsClient, String dbInstanceIdentifier) { try { DeleteDbInstanceRequest deleteDbInstanceRequest = DeleteDbInstanceRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .deleteAutomatedBackups(true) .skipFinalSnapshot(true) .build(); DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(deleteDbInstanceRequest); System.out.print("The status of the database is " + response.dbInstance().dbInstanceStatus()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } }
-
API 자세한 내용은 AWS SDK for Java 2.x API 참조의 DeleteDBInstance를 참조하세요.
-
다음 코드 예시에서는 DeleteDBParameterGroup
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. // Delete the parameter group after database has been deleted. // An exception is thrown if you attempt to delete the para group while database // exists. public static void deleteParaGroup(RdsClient rdsClient, String dbGroupName, String dbARN) throws InterruptedException { try { boolean isDataDel = false; boolean didFind; String instanceARN; // Make sure that the database has been deleted. while (!isDataDel) { DescribeDbInstancesResponse response = rdsClient.describeDBInstances(); List<DBInstance> instanceList = response.dbInstances(); int listSize = instanceList.size(); didFind = false; int index = 1; for (DBInstance instance : instanceList) { instanceARN = instance.dbInstanceArn(); if (instanceARN.compareTo(dbARN) == 0) { System.out.println(dbARN + " still exists"); didFind = true; } if ((index == listSize) && (!didFind)) { // Went through the entire list and did not find the database ARN. isDataDel = true; } Thread.sleep(sleepTime * 1000); index++; } } // Delete the para group. DeleteDbParameterGroupRequest parameterGroupRequest = DeleteDbParameterGroupRequest.builder() .dbParameterGroupName(dbGroupName) .build(); rdsClient.deleteDBParameterGroup(parameterGroupRequest); System.out.println(dbGroupName + " was deleted."); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
-
API 자세한 내용은 참조의 D eleteDBParameter그룹을 참조하세요. AWS SDK for Java 2.x API
-
다음 코드 예시에서는 DescribeAccountAttributes
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.AccountQuota; import software.amazon.awssdk.services.rds.model.RdsException; import software.amazon.awssdk.services.rds.model.DescribeAccountAttributesResponse; import java.util.List; /** * 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 DescribeAccountAttributes { public static void main(String[] args) { Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); getAccountAttributes(rdsClient); rdsClient.close(); } public static void getAccountAttributes(RdsClient rdsClient) { try { DescribeAccountAttributesResponse response = rdsClient.describeAccountAttributes(); List<AccountQuota> quotasList = response.accountQuotas(); for (AccountQuota quotas : quotasList) { System.out.println("Name is: " + quotas.accountQuotaName()); System.out.println("Max value is " + quotas.max()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } }
-
자세한 API 내용은 참조DescribeAccountAttributes의 섹션을 참조하세요. AWS SDK for Java 2.x API
-
다음 코드 예시에서는 DescribeDBEngineVersions
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. public static void describeDBEngines(RdsClient rdsClient) { try { DescribeDbEngineVersionsRequest engineVersionsRequest = DescribeDbEngineVersionsRequest.builder() .defaultOnly(true) .engine("mysql") .maxRecords(20) .build(); DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(engineVersionsRequest); List<DBEngineVersion> engines = response.dbEngineVersions(); // Get all DBEngineVersion objects. for (DBEngineVersion engineOb : engines) { System.out.println("The name of the DB parameter group family for the database engine is " + engineOb.dbParameterGroupFamily()); System.out.println("The name of the database engine " + engineOb.engine()); System.out.println("The version number of the database engine " + engineOb.engineVersion()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
-
API 자세한 내용은 AWS SDK for Java 2.x API 참조의 D escribeDBEngine버전을 참조하세요.
-
다음 코드 예시에서는 DescribeDBInstances
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse; import software.amazon.awssdk.services.rds.model.DBInstance; import software.amazon.awssdk.services.rds.model.RdsException; import java.util.List; /** * 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 DescribeDBInstances { public static void main(String[] args) { Region region = Region.US_EAST_1; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); describeInstances(rdsClient); rdsClient.close(); } public static void describeInstances(RdsClient rdsClient) { try { DescribeDbInstancesResponse response = rdsClient.describeDBInstances(); List<DBInstance> instanceList = response.dbInstances(); for (DBInstance instance : instanceList) { System.out.println("Instance ARN is: " + instance.dbInstanceArn()); System.out.println("The Engine is " + instance.engine()); System.out.println("Connection endpoint is" + instance.endpoint().address()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } }
-
API 자세한 내용은 AWS SDK for Java 2.x API 참조의 DescribeDBInstances를 참조하세요.
-
다음 코드 예시에서는 DescribeDBParameterGroups
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. public static void describeDbParameterGroups(RdsClient rdsClient, String dbGroupName) { try { DescribeDbParameterGroupsRequest groupsRequest = DescribeDbParameterGroupsRequest.builder() .dbParameterGroupName(dbGroupName) .maxRecords(20) .build(); DescribeDbParameterGroupsResponse response = rdsClient.describeDBParameterGroups(groupsRequest); List<DBParameterGroup> groups = response.dbParameterGroups(); for (DBParameterGroup group : groups) { System.out.println("The group name is " + group.dbParameterGroupName()); System.out.println("The group description is " + group.description()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
-
API 자세한 내용은 AWS SDK for Java 2.x API 참조의 D escribeDBParameter그룹을 참조하세요.
-
다음 코드 예시에서는 DescribeDBParameters
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. // Retrieve parameters in the group. public static void describeDbParameters(RdsClient rdsClient, String dbGroupName, int flag) { try { DescribeDbParametersRequest dbParameterGroupsRequest; if (flag == 0) { dbParameterGroupsRequest = DescribeDbParametersRequest.builder() .dbParameterGroupName(dbGroupName) .build(); } else { dbParameterGroupsRequest = DescribeDbParametersRequest.builder() .dbParameterGroupName(dbGroupName) .source("user") .build(); } DescribeDbParametersResponse response = rdsClient.describeDBParameters(dbParameterGroupsRequest); List<Parameter> dbParameters = response.parameters(); String paraName; for (Parameter para : dbParameters) { // Only print out information about either auto_increment_offset or // auto_increment_increment. paraName = para.parameterName(); if ((paraName.compareTo("auto_increment_offset") == 0) || (paraName.compareTo("auto_increment_increment ") == 0)) { System.out.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()); } } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
-
API 자세한 내용은 AWS SDK for Java 2.x API 참조의 DescribeDBParameters를 참조하세요.
-
다음 코드 예시에서는 DescribeOrderableDBInstanceOptions
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. // Get a list of allowed engine versions. public static void getAllowedEngines(RdsClient rdsClient, String dbParameterGroupFamily) { try { DescribeDbEngineVersionsRequest versionsRequest = DescribeDbEngineVersionsRequest.builder() .dbParameterGroupFamily(dbParameterGroupFamily) .engine("mysql") .build(); DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(versionsRequest); List<DBEngineVersion> dbEngines = response.dbEngineVersions(); for (DBEngineVersion dbEngine : dbEngines) { System.out.println("The engine version is " + dbEngine.engineVersion()); System.out.println("The engine description is " + dbEngine.dbEngineDescription()); } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
-
자세한 API 내용은 참조DescribeOrderableDBInstanceOptions의 섹션을 참조하세요. AWS SDK for Java 2.x API
-
다음 코드 예시에서는 GenerateRDSAuthToken
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. RdsUtilities
클래스를 사용하여 인증 토큰을 생성합니다. public class GenerateRDSAuthToken { public static void main(String[] args) { final String usage = """ Usage: <dbInstanceIdentifier> <masterUsername> Where: dbInstanceIdentifier - The database instance identifier.\s masterUsername - The master user name.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String dbInstanceIdentifier = args[0]; String masterUsername = args[1]; Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); String token = getAuthToken(rdsClient, dbInstanceIdentifier, masterUsername); System.out.println("The token response is " + token); } public static String getAuthToken(RdsClient rdsClient, String dbInstanceIdentifier, String masterUsername) { RdsUtilities utilities = rdsClient.utilities(); try { GenerateAuthenticationTokenRequest tokenRequest = GenerateAuthenticationTokenRequest.builder() .credentialsProvider(ProfileCredentialsProvider.create()) .username(masterUsername) .port(3306) .hostname(dbInstanceIdentifier) .build(); return utilities.generateAuthenticationToken(tokenRequest); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } return ""; } }
-
API 자세한 내용은 AWS SDK for Java 2.x API 참조의 G enerateRDSAuth토큰을 참조하세요.
-
다음 코드 예시에서는 ModifyDBInstance
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.ModifyDbInstanceRequest; import software.amazon.awssdk.services.rds.model.ModifyDbInstanceResponse; import software.amazon.awssdk.services.rds.model.RdsException; /** * 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 ModifyDBInstance { public static void main(String[] args) { final String usage = """ Usage: <dbInstanceIdentifier> <dbSnapshotIdentifier>\s Where: dbInstanceIdentifier - The database instance identifier.\s masterUserPassword - The updated password that corresponds to the master user name.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String dbInstanceIdentifier = args[0]; String masterUserPassword = args[1]; Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); updateIntance(rdsClient, dbInstanceIdentifier, masterUserPassword); rdsClient.close(); } public static void updateIntance(RdsClient rdsClient, String dbInstanceIdentifier, String masterUserPassword) { try { // For a demo - modify the DB instance by modifying the master password. ModifyDbInstanceRequest modifyDbInstanceRequest = ModifyDbInstanceRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .publiclyAccessible(true) .masterUserPassword(masterUserPassword) .build(); ModifyDbInstanceResponse instanceResponse = rdsClient.modifyDBInstance(modifyDbInstanceRequest); System.out.print("The ARN of the modified database is: " + instanceResponse.dbInstance().dbInstanceArn()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } }
-
API 자세한 내용은 AWS SDK for Java 2.x API 참조의 ModifyDBInstance을 참조하세요.
-
다음 코드 예시에서는 ModifyDBParameterGroup
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. // Modify auto_increment_offset and auto_increment_increment parameters. public static void modifyDBParas(RdsClient rdsClient, String dbGroupName) { try { Parameter parameter1 = Parameter.builder() .parameterName("auto_increment_offset") .applyMethod("immediate") .parameterValue("5") .build(); List<Parameter> paraList = new ArrayList<>(); paraList.add(parameter1); ModifyDbParameterGroupRequest groupRequest = ModifyDbParameterGroupRequest.builder() .dbParameterGroupName(dbGroupName) .parameters(paraList) .build(); ModifyDbParameterGroupResponse response = rdsClient.modifyDBParameterGroup(groupRequest); System.out.println("The parameter group " + response.dbParameterGroupName() + " was successfully modified"); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } }
-
API 자세한 내용은 참조의 M odifyDBParameter그룹을 참조하세요. AWS SDK for Java 2.x API
-
다음 코드 예시에서는 RebootDBInstance
을 사용하는 방법을 보여 줍니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.RebootDbInstanceRequest; import software.amazon.awssdk.services.rds.model.RebootDbInstanceResponse; import software.amazon.awssdk.services.rds.model.RdsException; /** * 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 RebootDBInstance { public static void main(String[] args) { final String usage = """ Usage: <dbInstanceIdentifier>\s Where: dbInstanceIdentifier - The database instance identifier\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String dbInstanceIdentifier = args[0]; Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); rebootInstance(rdsClient, dbInstanceIdentifier); rdsClient.close(); } public static void rebootInstance(RdsClient rdsClient, String dbInstanceIdentifier) { try { RebootDbInstanceRequest rebootDbInstanceRequest = RebootDbInstanceRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .build(); RebootDbInstanceResponse instanceResponse = rdsClient.rebootDBInstance(rebootDbInstanceRequest); System.out.print("The database " + instanceResponse.dbInstance().dbInstanceArn() + " was rebooted"); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } }
-
API 자세한 내용은 AWS SDK for Java 2.x API 참조의 RebootDBInstance을 참조하세요.
-
시나리오
다음 코드 예제는 Amazon Aurora Serverless 데이터베이스의 작업 항목을 추적하고 Amazon Simple Email Service(AmazonSES)를 사용하여 보고서를 전송하는 웹 애플리케이션을 생성하는 방법을 보여줍니다.
- SDK Java 2.x용
-
Amazon RDS 데이터베이스에 저장된 작업 항목을 추적하고 보고하는 웹 애플리케이션을 생성하는 방법을 보여줍니다.
Amazon Aurora Serverless 데이터를 쿼리RESTAPI하고 React 애플리케이션에서 사용할 Spring을 설정하는 방법에 대한 전체 소스 코드 및 지침은 의 전체 예제를 참조하세요GitHub
. 를 사용하는 예제를 설정하고 실행하는 방법에 대한 전체 소스 코드 및 지침은 의 전체 예제를 JDBC API참조하세요GitHub
. 이 예시에서 사용되는 서비스
Aurora
Amazon RDS
Amazon RDS Data Service
Amazon SES
서버리스 예제
다음 코드 예제는 RDS 데이터베이스에 연결하는 Lambda 함수를 구현하는 방법을 보여줍니다. 이 함수는 간단한 데이터베이스 요청을 하고 결과를 반환합니다.
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. 서버리스 예제
리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. Java를 사용하여 Lambda 함수의 Amazon RDS 데이터베이스에 연결합니다.
import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rdsdata.RdsDataClient; import software.amazon.awssdk.services.rdsdata.model.ExecuteStatementRequest; import software.amazon.awssdk.services.rdsdata.model.ExecuteStatementResponse; import software.amazon.awssdk.services.rdsdata.model.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class RdsLambdaHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) { APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent(); try { // Obtain auth token String token = createAuthToken(); // Define connection configuration String connectionString = String.format("jdbc:mysql://%s:%s/%s?useSSL=true&requireSSL=true", System.getenv("ProxyHostName"), System.getenv("Port"), System.getenv("DBName")); // Establish a connection to the database try (Connection connection = DriverManager.getConnection(connectionString, System.getenv("DBUserName"), token); PreparedStatement statement = connection.prepareStatement("SELECT ? + ? AS sum")) { statement.setInt(1, 3); statement.setInt(2, 2); try (ResultSet resultSet = statement.executeQuery()) { if (resultSet.next()) { int sum = resultSet.getInt("sum"); response.setStatusCode(200); response.setBody("The selected sum is: " + sum); } } } } catch (Exception e) { response.setStatusCode(500); response.setBody("Error: " + e.getMessage()); } return response; } private String createAuthToken() { // Create RDS Data Service client RdsDataClient rdsDataClient = RdsDataClient.builder() .region(Region.of(System.getenv("AWS_REGION"))) .credentialsProvider(DefaultCredentialsProvider.create()) .build(); // Define authentication request ExecuteStatementRequest request = ExecuteStatementRequest.builder() .resourceArn(System.getenv("ProxyHostName")) .secretArn(System.getenv("DBUserName")) .database(System.getenv("DBName")) .sql("SELECT 'RDS IAM Authentication'") .build(); // Execute request and obtain authentication token ExecuteStatementResponse response = rdsDataClient.executeStatement(request); Field tokenField = response.records().get(0).get(0); return tokenField.stringValue(); } }