Grails3 数据库关闭,程序自动重连

当服务器在运行过程中,数据库突然死掉,重启数据库发现连接不上数据库,需要重启项目才能解决

  • 方案一:配置数据库重连即可
environments:
    development:
        dataSource:
            dbCreate: '${jdbc.created}'
            url: '${jdbc.url}'
            properties:
              jmxEnabled: true
              initialSize: 5
              maxActive: 50
              minIdle: 5
              maxIdle: 25
              maxWait: 10000
              maxAge: 600000
              timeBetweenEvictionRunsMillis: 5000
              minEvictableIdleTimeMillis: 60000
              validationQuery: SELECT 1
              validationQueryTimeout: 3
              validationInterval: 15000
              testOnBorrow: true
              testWhileIdle: true
              testOnReturn: false
              jdbcInterceptors: ConnectionState
              defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
              # 自动重连,默认为false
              dbProperties:
                autoReconnect: true
  • 方案二:直接在url后面增加配置
jdbc:mysql://192.168.1.249:3306/test1?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true

更多详情

方案三:

HikariCP连接池

  • build.gradle中引入依赖
compile 'com.zaxxer:HikariCP:3.3.1'
  • 用了HikariCP连接池需要移除默认的tomcat-jdbc连接池
configurations {
//    compile.exclude module: 'commons'
    all*.exclude group: 'org.apache.tomcat', module: 'tomcat-jdbc'
}
  • 修改application.yml配置,连接池properties下面所有都注释掉
dataSource:
    # 关闭默认连接池
    pooled: false
#    jmxExport: true
    driverClassName: '${jdbc.driver}'
    username: '${jdbc.username}'
    password: '${jdbc.password}'
    url: '${jdbc.url}'
    dialect: org.hibernate.dialect.MySQL5InnoDBDialect
  • grails-app/conf/spring/resources.groovy中新增配置
package spring

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import grails.util.Holders

// Place your Spring DSL code here
beans = {

    def config = Holders.config

    hikari(HikariDataSource, { bean ->
        Properties hp = new Properties()
        hp.username = config.dataSource.username
        hp.password = config.dataSource.password
        hp.connectionTimeout = 6000
        hp.maximumPoolSize = 60
        hp.jdbcUrl = config.dataSource.url
        hp.driverClassName = config.dataSource.driverClassName

        // Hikari连接池
        HikariConfig hc = new HikariConfig(hp)
        bean.constructorArgs = [hc]
    })

}
  • 启动项目查看日志
17:55:02.779 [main] INFO  com.zaxxer.hikari.HikariDataSource (HikariDataSource.java:80) - HikariPool-1 - Starting...
17:55:02.827 [main] INFO  com.zaxxer.hikari.HikariDataSource (HikariDataSource.java:82) - HikariPool-1 - Start completed.

用了HikariCP连接池还能实现自动重连,比如:数据库宕了,重启数据库,程序也能自动连接上数据库

参考

发布了72 篇原创文章 · 获赞 38 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_16165281/article/details/91583646
今日推荐