[英]How to make Spring Boot application run despite whether a datasource is available
在我的 Spring Boot 应用程序中,配置了一个数据源。 application.properties
就像:
spring.datasource.url=jdbc:mysql://localhost/test_db
spring.datasource.username=test
spring.datasource.password=test
应用程序代码如下所示:
public class Foo {
@Autowired
private JdbcTemplate jdbcTemplate;
private List<String> getDataFromDB(String user) {
List<String> data = jdbcTemplate.query(
"SELECT ... FROM ...;", /* the detail ommited */);
return data;
}
}
该代码工作正常。 但是,如果数据库服务器不可用,Spring Boot 将无法启动:
2018-01-17 14:03:30.310 ERROR o.a.tomcat.jdbc.pool.ConnectionPool [182][main][][][] Unable to create initial connections of pool.
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.
...
2018-01-17 14:03:30.314 WARN o.h.e.jdbc.internal.JdbcServicesImpl [204][main][][][] HHH000342: Could not obtain connection to query metadata : 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.
2018-01-17 14:03:30.318 WARN ationConfigEmbeddedWebApplicationContext[546][main][][][] Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
2018-01-17 14:03:30.336 ERROR o.s.boot.SpringApplication [827][main][][][] Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
...
Process finished with exit code 1
我省略了多行错误消息。
在我的应用程序中,数据库不是必需的,它仅用于改进。 即使数据库不可用,我也想运行该应用程序,但会注意到此类失败。
如何实现这一目标?
尝试设置 spring.datasource.continue-on-error=true
如果无法通过设置以下参数连接到数据库,我可以让我的 Spring Boot 应用程序继续运行:
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.