假設我有一個具有 starter-JPA 依賴項的 spring-boot 應用程式。我需要知道spring是否在啟動時檢查與資料庫的連接?
例如,如果我提到了一個我無權訪問的資料庫(如下所示),應用程式會無法啟動嗎?如果是,會有什么例外?
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.dialect=org.hibernate.dialect.PostgreSQL94Dialect
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.continue-on-error=true
uj5u.com熱心網友回復:
對于 Spring Boot 2.7.2 的最后一個版本,Spring Boot 本身并不檢查連接,而是獲取連接以確定某些屬性。Hibernate 還需要一個連接來確定某些屬性本身(由 控制spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults)。
此外,如果您有spring-boot-starter-actuator依賴項,則將在啟動時檢查連接(由 控制management.health.db.enabled)。
它需要明確指定所有自動確定的屬性以在啟動期間不獲取連接(甚至spring.jpa.hibernate.ddlAuto)
將此添加到application.yaml
spring.jpa.hibernate.ddlAuto: "none"
spring.datasource.driver-class-name: org.postgresql.Driver
spring.jpa.database-platform: org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults: false #Hibernate
# disable datasource check on startup
management.health.db.enabled: false #spring-boot-starter-actuator
默認情況下,Hikari 用作連接池。連接池在第一次嘗試獲取連接時獲取所有連接。這就是為什么它在啟動期間無法獲得連接的原因。
uj5u.com熱心網友回復:
沒什么。只需執行您的查詢。如果連接已斷開,您的 JDBC 驅動程式將重新連接(如果它支持它,并且您在連接字串中啟用了它——大多數不支持它),否則您將得到一個例外。
我們最好的機會是對一個表執行一個簡單的查詢,例如:
select 1 from SOME_TABLE;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/515518.html
