我有一个AWS上的Postgres数据库,可以在外面使用。当我在本地启动我的应用程序时,连接工作正常。
当我在AWS Lambda上启动它时,出现此错误:
org.postgresql.util.PSQLException: The connection attempt failed.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:292)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
at org.postgresql.Driver.makeConnection(Driver.java:454)
at org.postgresql.Driver.connect(Driver.java:256)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at ninja.majewski.AmazonDbService.getRemoteConnection(AmazonDbService.java:84)
at ninja.majewski.AmazonDbService.removeOldDeals(AmazonDbService.java:63)
at ninja.majewski.ChinaStuffLambdaHandler.handleRequest(ChinaStuffLambdaHandler.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at lambdainternal.EventHandlerLoader$PojoMethodRequestHandler.handleRequest(EventHandlerLoader.java:259)
at lambdainternal.EventHandlerLoader$PojoHandlerAsStreamHandler.handleRequest(EventHandlerLoader.java:178)
at lambdainternal.EventHandlerLoader$2.call(EventHandlerLoader.java:888)
at lambdainternal.AWSLambda.startRuntime(AWSLambda.java:292)
at lambdainternal.AWSLambda.<clinit>(AWSLambda.java:64)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at lambdainternal.LambdaRTEn
try.main(LambdaRTEntry.java:94)
这是失败的代码:
private Connection getRemoteConnection() throws Exception {
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;
log.info(String.format("Logging to DB: %s", jdbcUrl));
return DriverManager.getConnection(jdbcUrl);
}
这可能是什么原因?
答案 0 :(得分:0)
您必须在lambda中配置Network
参数。您必须添加一个VPC
和一个Security Group
。
将此安全组添加到您的lambda后,您将转到 网络和安全->安全组中的 EC2管理控制台 em> 。在这里,您可以选择RDS实例的安全组,然后编辑Inbound
参数。您添加了Type
的PostgreSQL和Custom Source
,其名称为您刚添加到Lambda的安全组的名称。