本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
将亚马逊RDS数据库实例添加到你的 Java Elastic Beanstalk 环境中
本主题提供RDS使用 Elastic Beanstalk 控制台创建亚马逊的说明。您可以使用 Amazon Relational Database Service (AmazonRDS) 数据库实例来存储您的应用程序收集和修改的数据。数据库可以附加到您的环境并由 Elastic Beanstalk 进行管理,也可以在外部创建和管理数据库。
如果您是首次使用亚马逊RDS,请使用 Elastic Beanstalk 控制台将数据库实例添加到测试环境中,并验证您的应用程序是否可以连接到该实例。
向环境添加数据库实例
打开 Elastic Beanstalk
控制台,然后在 “区域” 列表中,选择您的。 Amazon Web Services 区域 -
在导航窗格中,选择 Environments(环境),然后从列表中选择环境的名称。
注意
如果您有多个环境,请使用搜索栏筛选环境列表。
在导航窗格中,选择 Configuration (配置)。
-
在 Database(数据库)配置类别中,选择 Edit(编辑)。
-
选择数据库引擎,然后输入用户名和密码。
-
要保存更改,请选择页面底部的 Apply(应用)。
添加一个数据库实例大约需要 10 分钟。环境更新完成后,您的应用程序就可以通过以下环境属性访问数据库实例的主机名和其他连接信息:
属性名称 | 描述 | 属性值 |
---|---|---|
|
数据库实例的主机名。 |
在 Amazon RDS 控制台的 “连接和安全” 选项卡上:终端节点。 |
|
数据库实例接受连接的端口。默认值因数据库引擎而异。 |
在 Amazon RDS 控制台的 “连接和安全” 选项卡上:端口。 |
|
数据库名称 |
在 Amazon RDS 控制台的配置选项卡上:数据库名称。 |
|
您为数据库配置的用户名。 |
在 Amazon RDS 控制台的配置选项卡上:主用户名。 |
|
您为数据库配置的密码。 |
在 Amazon RDS 控制台中不可参考。 |
有关配置内部数据库实例的更多信息,请参阅将数据库添加到 Elastic Beanstalk 环境。有关配置外部数据库以用于 Elastic Beanstalk 的说明,请参阅在亚马逊上使用 Elastic Beanstalk RDS。
要连接到数据库,请向应用程序添加相应的驱动程序JAR文件,在代码中加载驱动程序类,然后使用 Elastic Beanstalk 提供的环境属性创建一个连接对象。
正在下载JDBC驱动程序
您将需要所选数据库引擎的JDBC驱动程序JAR文件。将JAR文件保存在源代码中,并在编译用于创建数据库连接的类时将其包含在类路径中。
在以下位置可以找到数据库引擎的最新驱动程序:
-
我的 SQL — 我的SQL连接器/J
-
甲骨文 SE-1 — 甲骨文驱动程序 JDBC
-
SQL服务器 — 微软JDBC驱动程序
要使用JDBC驱动程序,请在代码DriverManager.getConnection()
中创建与的连接之前调Class.forName()
用将其加载。
JDBC使用以下格式的连接字符串:
jdbc:driver
://hostname
:port
/dbName
?user=userName
&password=password
您可以从 Elastic Beanstalk 提供给应用程序的环境变量中检索主机名、端口、数据库名称、用户名和密码。驱动程序名称特定于您的数据库类型和驱动程序版本。以下是驱动程序名称示例:
-
mysql
为了我的 SQL -
postgresql
适用于 Postgr SQL -
oracle:thin
适用于 Oracle Thin -
oracle:oci
对于甲骨文 OCI -
oracle:oci8
适用于甲骨文 OCI 8 -
oracle:kprb
对于甲骨文 KPRB -
sqlserver
用于SQL服务器
连接数据库 (Java SE 平台)
在 Java SE 环境中,可以使用 System.getenv()
从环境中读取连接变量。以下示例代码显示了一个用于创建与 Postgre SQL 数据库的连接的类。
private static Connection getRemoteConnection() {
if (System.getenv("RDS_HOSTNAME") != null) {
try {
Class.forName("org.postgresql.Driver");
String dbName = System.getenv("RDS_DB_NAME");
String userName = System.getenv("RDS_USERNAME");
String password = System.getenv("RDS_PASSWORD");
String hostname = System.getenv("RDS_HOSTNAME");
String port = System.getenv("RDS_PORT");
String jdbcUrl = "jdbc:postgresql://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password=" + password;
logger.trace("Getting remote connection with connection string from environment variables.");
Connection con = DriverManager.getConnection(jdbcUrl);
logger.info("Remote connection successful.");
return con;
}
catch (ClassNotFoundException e) { logger.warn(e.toString());}
catch (SQLException e) { logger.warn(e.toString());}
}
return null;
}
连接数据库 (Tomcat 平台)
在 Tomcat 环境中,环境属性是以 System.getProperty()
可访问的系统属性的形式提供的。
以下示例代码显示了一个用于创建与 Postgre SQL 数据库的连接的类。
private static Connection getRemoteConnection() {
if (System.getProperty("RDS_HOSTNAME") != null) {
try {
Class.forName("org.postgresql.Driver");
String dbName = System.getProperty("RDS_DB_NAME");
String userName = System.getProperty("RDS_USERNAME");
String password = System.getProperty("RDS_PASSWORD");
String hostname = System.getProperty("RDS_HOSTNAME");
String port = System.getProperty("RDS_PORT");
String jdbcUrl = "jdbc:postgresql://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password=" + password;
logger.trace("Getting remote connection with connection string from environment variables.");
Connection con = DriverManager.getConnection(jdbcUrl);
logger.info("Remote connection successful.");
return con;
}
catch (ClassNotFoundException e) { logger.warn(e.toString());}
catch (SQLException e) { logger.warn(e.toString());}
}
return null;
}
如果您在获取连接或运行SQL语句时遇到问题,请尝试将以下代码放在JSP文件中。此代码连接数据库实例,创建一个表并向表中写入。
<%@ page import="java.sql.*" %>
<%
// Read RDS connection information from the environment
String dbName = System.getProperty("RDS_DB_NAME");
String userName = System.getProperty("RDS_USERNAME");
String password = System.getProperty("RDS_PASSWORD");
String hostname = System.getProperty("RDS_HOSTNAME");
String port = System.getProperty("RDS_PORT");
String jdbcUrl = "jdbc:mysql://" + hostname + ":" +
port + "/" + dbName + "?user=" + userName + "&password=" + password;
// Load the JDBC driver
try {
System.out.println("Loading driver...");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot find the driver in the classpath!", e);
}
Connection conn = null;
Statement setupStatement = null;
Statement readStatement = null;
ResultSet resultSet = null;
String results = "";
int numresults = 0;
String statement = null;
try {
// Create connection to RDS DB instance
conn = DriverManager.getConnection(jdbcUrl);
// Create a table and write two rows
setupStatement = conn.createStatement();
String createTable = "CREATE TABLE Beanstalk (Resource char(50));";
String insertRow1 = "INSERT INTO Beanstalk (Resource) VALUES ('EC2 Instance');";
String insertRow2 = "INSERT INTO Beanstalk (Resource) VALUES ('RDS Instance');";
setupStatement.addBatch(createTable);
setupStatement.addBatch(insertRow1);
setupStatement.addBatch(insertRow2);
setupStatement.executeBatch();
setupStatement.close();
} catch (SQLException ex) {
// Handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
System.out.println("Closing the connection.");
if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
}
try {
conn = DriverManager.getConnection(jdbcUrl);
readStatement = conn.createStatement();
resultSet = readStatement.executeQuery("SELECT Resource FROM Beanstalk;");
resultSet.first();
results = resultSet.getString("Resource");
resultSet.next();
results += ", " + resultSet.getString("Resource");
resultSet.close();
readStatement.close();
conn.close();
} catch (SQLException ex) {
// Handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
System.out.println("Closing the connection.");
if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
}
%>
要显示结果,请将以下代码放在JSP文件HTML部分的正文中。
<p>Established connection to RDS. Read first two rows: <%= results %></p>
数据库连接问题排查
如果您从应用程序中连接数据库时遇到问题,请查看 Web 容器日志和数据库。
查看日志
您可以从 Eclipse 中查看 Elastic Beanstalk 环境中的所有日志。如果您没有打开 Amazon 资源管理器视图,请选择工具栏中橙色 Amazon 图标旁边的箭头,然后选择 “显示 Amazon 资源管理器视图”。展开 Amazon Elastic Beanstalk 和您的环境名称,然后打开服务器的上下文(右键单击)菜单。选择 “在WTP服务器编辑器中打开”。
选择 Server(服务器)视图的 Log(日志)选项卡以查看环境中的聚合日志。要打开最新日志,请选择页面右上角的 Refresh(刷新)按钮。
向下滚动以在 /var/log/tomcat7/catalina.out
中找到 Tomcat 日志。如果您已在前面的示例中多次加载网页,可能会看到以下内容。
-------------------------------------
/var/log/tomcat7/catalina.out
-------------------------------------
INFO: Server startup in 9285 ms
Loading driver...
Driver loaded!
SQLException: Table 'Beanstalk' already exists
SQLState: 42S01
VendorError: 1050
Closing the connection.
Closing the connection.
Web 应用程序发送到标准输出的所有信息都会显示在 Web 容器日志中。在上一示例中,每次加载页面时,应用程序都会尝试创建表。这会导致在第一次加载页面之后每次加载页面时都会捕获SQL异常。
作为示例,上述行为是可接受的。但在实际应用程序中,应将数据库定义保留在架构对象中,从模型类中执行事务并与控制器 servlet 协调请求。
连接到 RDS 数据库实例
您可以使用 “我的客户端” 应用程序直接连接到 Elastic Beanstalk 环境中的RDS数据库实例。SQL
首先,打开RDS数据库实例的安全组以允许来自您的计算机的流量。
打开 Elastic Beanstalk
控制台,然后在 “区域” 列表中,选择您的。 Amazon Web Services 区域 -
在导航窗格中,选择 Environments(环境),然后从列表中选择环境的名称。
注意
如果您有多个环境,请使用搜索栏筛选环境列表。
在导航窗格中,选择 Configuration (配置)。
-
在 Database(数据库)配置类别中,选择 Edit(编辑)。
-
在 Endpo int 旁边,选择亚马逊RDS控制台链接。
-
在RDS控制面板实例详细信息页面的安全和网络下,选择安全组旁边以 r ds- 开头的安全组。
注意
数据库可能有多个标记为 Security Groups(安全组)的条目。只有当你的旧账户没有默认的亚马逊虚拟私有云(Amazon)时,才使用第一个以 awseb 开头的账户。VPC
-
在 Security group details(安全组详细信息)中,选择 Inbound(入站)选项卡,然后选择 Edit(编辑)。
-
为 MySQL(端口 3306)添加一条规则,允许来自您的 IP 地址的流量(格式指定)。CIDR
-
选择保存。更改将立即生效。
返回到环境的 Elastic Beanstalk 配置详细信息并记下终端节点。您将使用域名连接到RDS数据库实例。
安装我的SQL客户端,并在端口 3306 上启动与数据库的连接。在 Windows 上,从 “我的SQL主页” 安装 “我的SQL工作台”,然后按照提示进行操作。
在 Linux 上,使用软件包管理器为你的发行版安装 “我的SQL客户端”。以下示例对 Ubuntu 和其他 Debian 衍生物有效。
// Install MySQL client
$ sudo apt-get install mysql-client-5.5
...
// Connect to database
$ mysql -h aas839jo2vwhwb.cnubrrfwfka8.us-west-2.rds.amazonaws.com
-u username
-ppassword
ebdb
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 117
Server version: 5.5.40-log Source distribution
...
连接后,您可以运行SQL命令来查看数据库的状态、表和行是否已创建以及其他信息。
mysql> SELECT Resource from Beanstalk;
+--------------+
| Resource |
+--------------+
| EC2 Instance |
| RDS Instance |
+--------------+
2 rows in set (0.01 sec)