【问题标题】:Spring Boot and Hibernate: Start an application even if a connection to the database is not availableSpring Boot 和 Hibernate:即使与数据库的连接不可用也启动应用程序
【发布时间】:2017-04-21 17:45:27
【问题描述】:

我的 Spring Boot 应用程序需要连接到两个不同的数据库。第一个数据库(主)与 localhost 应用程序安装在同一台服务器上,另一个数据库(辅助)安装在远程服务器上,并且并不总是可用(用于维护、备份、测试等)。

我使用以下配置(application.properties)。

# main connection
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/?autoReconnect=true&verifyServerCertificate=false&useSSL=false&requireSSL=false
spring.datasource.username=emater
spring.datasource.password=emater

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# secondary connection
planejamento.datasource.driverClassName=com.mysql.jdbc.Driver
planejamento.datasource.url=jdbc:mysql://10.22.1.4/?verifyServerCertificate=false&useSSL=false&requireSSL=false
planejamento.datasource.username=emater
planejamento.datasource.password=emater
planejamento.datasource.testWhileIdle = false

#config hibernate
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQLSpatial56Dialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
spring.jpa.show-sql=true
spring.jpa.format-sql=true
spring.jpa.use-sql-comments=true
spring.jpa.hibernate.enable_lazy_load_no_trans=true

在初始化应用程序时,hibernate 会尝试连接到两个数据库。如果此时第二个数据库不可用,则会引发异常并中止应用程序初始化。

我可以使用任何属性来防止我的应用程序在启动时中止吗?

我该怎么办?

【问题讨论】:

标签: java spring hibernate spring-boot database-connection


【解决方案1】:

Hibernate 需要在SessionFactory 时连接到数据库,以便我可以从数据库Connection 中提取DatabaseMetaData

DatabaseMetaData,需要查一下:

  • 当前目录和架构
  • 如何限定标识符
  • 如果数据库支持临时表
  • 如果 DDL 导致事务提交
  • 如果驱动程序支持可滚动ResultSet
  • 如果驱动程序支持批量更新
  • 如果驱动程序返回为 IDENTITY 列生成的键

这个信息在SessionFactory被初始化时被解析,所以你最好懒惰地启动一个新的微服务,当相关的数据库也可用时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-07
    • 2021-11-19
    • 1970-01-01
    • 2015-05-31
    • 2020-07-13
    • 2018-09-30
    • 1970-01-01
    • 2021-03-01
    相关资源
    最近更新 更多