gpt4 book ai didi

java - 如何让 Spring Boot 应用程序在数据源是否可用的情况下运行

转载 作者:太空宇宙 更新时间:2023-11-04 10:46:58 25 4
gpt4 key购买 nike

在我的 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

关于java - 如何让 Spring Boot 应用程序在数据源是否可用的情况下运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48294704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com