我有一个在ec2实例中运行的mysql,当我尝试使用那个mysql时,我可以这样做:
dilin-mbp:~ dilin$ ssh -i /Users/dilin/Documents/SelfProject/MM_AWS_MainKey.pem ec2-user@54.69.23.214
Last login: Tue Feb 24 05:07:47 2015 from c-73-189-116-135.hsd1.ca.comcast.net
__| __|_ )
_| ( / Amazon Linux AMI
___|\___|___|
https://aws.amazon.com/amazon-linux-ami/2014.09-release-notes/
[ec2-user@ip-172-31-45-13 ~]$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1969
Server version: 5.5.42 MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select * from .....;
也就是说,我需要首先使用pem文件访问服务器然后我可以使用mysql。
问题是,在JDBC中,如何配置pem文件以使自己连接?
我天真的实施:
String url = "jdbc:mysql://54.69.23.214:3306/";
String dbName = "snapsono";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "pwd";
SnapList snapList = new SnapList();
try {
Driver mysqlDriver = (Driver) Class.forName(driver).newInstance();
DriverManager.registerDriver(mysqlDriver);
logger.info("about to get access");
Connection conn = DriverManager.getConnection(url + dbName,
userName, password);
logger.info("get Initialized!!!");
Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM event");
while (res.next()) {
int id = res.getInt("userid");
String idUrl = res.getString("url");
SnapProfile profile = new SnapProfile(id,idUrl);
snapList.getList().add(profile);
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
在目前的实现中,根据日志,我无法设置连接,而服务器也没有响应。我想这是因为我没有设置pem文件,任何人都可以帮我指出设置吗?
[INFO] Starting scanner at interval of 40 seconds.
Feb 24, 2015 8:51:16 PM snap.sono.demo.impl.GeneralImpl getDbHello
INFO: >>> enter getDbHello
Feb 24, 2015 8:51:16 PM snap.sono.demo.impl.GeneralImpl getDbHello
INFO: about to get access
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
由于
答案 0 :(得分:0)
这是因为您的AWS实例配置为仅从localhost连接到端口3306,更准确地说,它只允许从EC2-Instance IP连接。
所以,
登录到您的AWS Console
并修改已分配的Security Group Policy
,并将其设置为允许从任意IP进行连接。
您可以参考此链接来编辑安全组策略,它适用于SSH,但MySQL的过程相同,只是您需要为MySQL添加新规则。
.AWS REF.
其次,创建一个新的mysql用户如下
create user 'appuser'@'localhost' identified by 'pass123';
create user 'appuser'@'%' identified by 'pass123';
grant all privileges on *.* to 'appuser'@'localhost'
grant all privileges on *.* to 'appuser'@'%';
这样您就可以从任何IP连接到mysql
,或者如果您有静态IP,那么出于安全考虑,我建议您使用它代替%
:)