Guide to AWS Aurora RDS with Java – 使用Java的AWS Aurora RDS指南

最后修改: 2018年 9月 16日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

Amazon Aurora is a MySQL and PostgreSQL compatible relational database built for the cloud that combines the performance and availability of high-end commercial databases with the simplicity and cost-effectiveness of open source databases.

Amazon Aurora是一个兼容MySQL和PostgreSQL的关系型数据库,专为云计算而构建,它结合了高端商业数据库的性能和可用性以及开源数据库的简单性和成本效益。

In this tutorial, we’ll cover how to create and interact with Amazon RDS instance with Java, we’ll also connect and execute SQL tests on Amazon RDS.

在本教程中,我们将介绍如何用Java创建亚马逊RDS实例并与之互动,我们还将在亚马逊RDS上连接并执行SQL测试。

Let’s start by setting up the project.

让我们从设置项目开始。

2. Maven Dependencies

2.Maven的依赖性

Let’s create a Java Maven project and add AWS SDK to our project:

让我们创建一个Java Maven项目并将AWS SDK添加到我们的项目中。

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>1.11.377</version>
</dependency>

To view the latest version, check Maven Central.

要查看最新版本,请查看Maven Central

3. Prerequisites

3.先决条件

To use AWS SDK, we’ll need a few things to setup:

为了使用AWS SDK,我们需要一些东西来设置。

  • AWS Account
  • AWS Security Credentials
  • Choosing AWS Region

We need an Amazon Web Services account. If you still don’t have any, go ahead and create an account

我们需要一个亚马逊网络服务账户。如果你还没有,请继续创建一个账户

AWS Security Credentials are the access keys that allow us to make programmatic calls to AWS API actions. We can get these credentials in two ways, either by using AWS root account credentials from access keys section of the Security Credentials page or by using IAM user credentials from IAM console

AWS 安全凭证是允许我们对 AWS API 操作进行编程调用的访问密钥。我们可以通过两种方式获得这些凭证,一种是使用安全凭证页面的访问密钥部分的AWS根帐户凭证,另一种是使用IAM控制台的IAM用户凭证

We have to select an AWS region(s) where we want to store our Amazon RDS. Keep in mind that RDS prices vary by region. For more details, head over to the official documentation.

我们必须选择一个AWS区域,在那里我们要存储我们的Amazon RDS。请记住,RDS的价格因地区而异。欲了解更多细节,请前往官方文档

For this tutorial, we’ll use Asia Pacific (Sydney) (region ap-southeast-2).

在本教程中,我们将使用亚太地区(悉尼)(区域ap-southeast-2)。

4. Connect to AWS RDS Webservices

4.连接到AWS RDS Webservices

First, we need to create a client connection to access Amazon RDS web service.

首先,我们需要创建一个客户端连接来访问亚马逊RDS网络服务。

We’ll use AmazonRDS interface for this purpose:

我们将为此目的使用AmazonRDS接口。

AWSCredentials credentials = new BasicAWSCredentials(
  "<AWS accesskey>", 
  "<AWS secretkey>"
);

Then configure the RDS Builder with the appropriate region and credentials:

然后配置RDS生成器与适当的区域证书

AmazonRDSClientBuilder.standard().withCredentials(credentials)
  .withRegion(Regions.AP_SOUTHEAST_2)
  .build();

5. Amazon Aurora Instance

5.亚马逊Aurora实例

Now let’s create the Amazon Aurora RDS instance.

现在让我们来创建亚马逊Aurora RDS实例。

5.1. Create RDS Instance

5.1.创建RDS实例

To create the RDS instance, we need to instantiate a CreateDBInstanceRequest with the following attributes:

为了创建RDS实例,我们需要实例化一个CreateDBInstanceRequest,并具有以下属性。

  • DB Instance Identifier that is unique across all existing instances names in Amazon RDS
  • DB Instance class specify configuration for CPU, ECU, Memory, etc., from Instance Class Table
  • Database Engine. PostgreSQL or MySQL, we’ll use PostgreSQL
  • Database master/super username
  • Database master user password
  • DB name to create an initial database with the specified name
  • For Storage Type, specify an Amazon EBS volume type. The list is available here
  • Storage allocation in GiB
CreateDBInstanceRequest request = new CreateDBInstanceRequest();
request.setDBInstanceIdentifier("baeldung");   
request.setDBInstanceClass("db.t2.micro");
request.setEngine("postgres");
request.setMultiAZ(false);
request.setMasterUsername("username");
request.setMasterUserPassword("password");
request.setDBName("mydb");       
request.setStorageType("gp2");   
request.setAllocatedStorage(10);

Now let’s create our first instance by calling the createDBInstance(): 

现在让我们通过调用createDBInstance()来创建我们的第一个实例:

amazonRDS.createDBInstance(request);

RDS instance will be created in a few minutes.

RDS实例将在几分钟内被创建。

We won’t get the endpoint URL in the response as this call is asynchronous.

我们不会在响应中获得端点URL,因为这个调用是异步的。

5.2. List DB Instance

5.2.列表 DB 实例

In this section, we’ll see how to list the created DB instance.

在本节中,我们将看到如何列出已创建的DB实例。

To list the RDS instance, we need to use describeDBInstances of the AmazonRDS interface:

为了列出RDS实例,我们需要使用describeDBInstancesAmazonRDS接口:

DescribeDBInstancesResult result = amazonRDS.describeDBInstances();
List<DBInstance> instances = result.getDBInstances();
for (DBInstance instance : instances) {
    // Information about each RDS instance
    String identifier = instance.getDBInstanceIdentifier();
    String engine = instance.getEngine();
    String status = instance.getDBInstanceStatus();
    Endpoint endpoint = instance.getEndpoint();
}

Endpoint URL is the connection URL for our new DB instance. This URL will be provided as a host while connecting to the database.

端点URL是我们新的数据库实例的连接URL。这个URL将在连接到数据库时作为主机提供。

5.3. Run JDBC Test

5.3 运行JDBC测试

Now let’s connect our RDS instance and create our first table.

现在让我们连接我们的RDS实例并创建我们的第一个表。

Let’s create a db.properties file and add the database information:

让我们创建一个db.properties文件并添加数据库信息。

db_hostname=<Endpoint URL>
db_username=username
db_password=password
db_database=mydb

After creating the file, let’s connect to RDS instance and create the table named jdbc_test:

创建文件后,让我们连接到RDS实例并创建名为jdbc_test的表。

Properties prop = new Properties();
InputStream input = AwsRdsDemo.class.getClassLoader().getResourceAsStream("db.properties");
prop.load(input);
String db_hostname = prop.getProperty("db_hostname");
String db_username = prop.getProperty("db_username");
String db_password = prop.getProperty("db_password");
String db_database = prop.getProperty("db_database");
Connection conn = DriverManager.getConnection(jdbc_url, db_username, db_password);
Statement statement = conn.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS jdbc_test (id SERIAL PRIMARY KEY, content VARCHAR(80))";
statement.executeUpdate(sql);

Afterward, we’ll insert and retrieve data from the table:

之后,我们将从表中插入和检索数据:

PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO jdbc_test (content) VALUES (?)");
String content = "" + UUID.randomUUID();
preparedStatement.setString(1, content);
preparedStatement.executeUpdate();
String sql = "SELECT  count(*) as count FROM jdbc_test";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
    String count = resultSet.getString("count");
    Logger.log("Total Records: " + count);
}

5.4. Delete the Instance

5.4.删除实例

To delete DB instance, we need to generate DeleteDBInstanceRequest. It requires the DB instance identifier and skipFinalSnapshot parameter.

要删除DB实例,我们需要生成DeleteDBInstanceRequest。它需要DB实例标识符和skipFinalSnapshot参数。

The skipFinalSanpshot is to specify if we want to take the snapshot before deleting the instance:

skipFinalSanpshot是为了指定我们是否要在删除实例之前进行快照。

DeleteDBInstanceRequest request = new DeleteDBInstanceRequest();
request.setDBInstanceIdentifier(identifier);
request.setSkipFinalSnapshot(true);
DBInstance instance = amazonRDS.deleteDBInstance(request);

6. Conclusion

6.结语

In this article, we focused on the basics of interacting with the Amazon Aurora (PostgreSQL) RDS via Amazon SDK. This tutorial has focused on PostgreSQL there are also other options including MySQL.

在这篇文章中,我们着重介绍了通过亚马逊SDK与亚马逊Aurora(PostgreSQL)RDS互动的基本知识。本教程的重点是PostgreSQL,也有其他选择,包括MySQL。

Although the interaction method will remain the same across RDS. Aurora is a preferred choice for many customers because it is up to five times faster than standard MySQL databases and three times faster than standard PostgreSQL databases.

尽管在整个RDS中,交互方法将保持不变。Aurora是许多客户的首选,因为它比标准MySQL数据库快5倍,比标准PostgreSQL数据库快3倍。

For more information visit Amazon Aurora.

更多信息请访问Amazon Aurora

And, as always, the code can be found over on Github.

而且,像往常一样,代码可以在Github上找到over