AWS Aurora无服务器Spring Boot通信链接错误

时间:2020-08-01 13:29:35

标签: java amazon-web-services spring-boot serverless aurora

我正在做一个原型,将基于Spring Boot的应用程序迁移到包括无服务器模式的AWS Aurora DB。使用预配置模式,一切正常。但是,在无服务器模式下,应用程序无法从EC2实例连接到数据库,但例外情况如下:

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'entityManagerFactory' defined in class path resource 
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: 
Invocation of init method failed; nested exception is javax.persistence.PersistenceException: 
[PersistenceUnit: default] Unable to build Hibernate SessionFactory; 
nested exception is org.hibernate.exception.JDBCConnectionException: 
Unable to open JDBC Connection for DDL execution

.....

Caused by: com.mysql.cj.jdbc.exceptions.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.

我尝试减小初始池大小等,但仍然收到相同的错误

spring.datasource.url=jdbc:mysql://xxxxxx.cluster-xxxxxxxxxx.us-east-1.rds.amazonaws.com:3306/db_example
spring.datasource.username=xxxx
spring.datasource.password=xxxxxxx
spring.datasource.hikari.maximum-pool-size=1
spring.datasource.hikari.minimum-idle=0
spring.datasource.hikari.connection-timeout=60000
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
....

当我将数据源更改为SimpleDataSource或从EC2实例运行简单的Java jdbc连接时,它将起作用。

@Bean("dataSource")
public DataSource dataSource() {
  SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
  ....
}     

Spring Boot JPA / JDBC应用程序正常吗?我们必须使用SimpleDriverDataSource吗?也许我们宁可使用https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html?那可能是重写很多与数据库相关的代码。

1 个答案:

答案 0 :(得分:2)

在无服务器模式下,尽管通过准备就绪的实例池进行了高度优化,但是您的应用程序需要一些时间才能真正连接到Aurora。

由于这个原因,很可能在应用程序启动时与数据库的连接尚不可用。

对于您的错误跟踪,似乎您正在尝试执行某种DDL操作,这可能是因为您正在使用hbm2ddl创建或验证数据库模式,并且此操作需要在应用程序启动时进行连接。 / p>

为了支持这种数据库体系结构,您可以延迟初始化bean(在实体管理器和Hibernate的情况下可能是基石),或者寻找诸如Liquibase之类的DDL生成的替代方法(尽管我认为问题仍然存在。)

您可以尝试调整Hikari连接参数。例如,本文提出了一个聪明的配置,并提供了对AWS Aurora的深入了解:

https://silexdata.com/modern-applications-and-aws-aurora-serverless/

我唯一不了解的是为什么您的代码可以与SimpleDriverDataSource一起使用:也许它提供了一些默认值,这些默认值使您的应用程序从一开始就可以毫无错误地连接到Aurora。