Spring数据 - 如果主数据源失败,则第二个数据源不会出现

时间:2017-10-28 16:13:48

标签: spring hibernate jpa spring-boot spring-data

我正在使用Spring启动和Spring数据,我想主要使用MySQL数据源,但如果连接失败则转到H2数据源。

到目前为止,我只是在配置中移动@Primary进行更改,但是如果我将@Primary放在MySQL(主数据源)中并在我的电脑中停止MySQL服务器,则另一个bean不会出现......我需要什么?

application.yml:

# Main properties
spring:
  application:
    name: app
  jpa:
    database: default
    show-sql: false
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        format_sql: false
        current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext

# Main database: MySQL
main.datasource:
  url: jdbc:mysql://localhost:3306/app?useSSL=false
  driver-class-name: com.mysql.jdbc.Driver
  username: sa
  password: sa

# Backup database: H2
backup.datasource:
  url: jdbc:h2:${project.directory}/app;DB_CLOSE_ON_EXIT=FALSE
  driver-class-name: org.h2.Driver
  username: sa
  password: sa

主要数据源

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("org.app")
@EntityScan("org.app")
public class MainDataSourceConfig {

    @Primary
    @Bean(name = "mainDataSource")
    @ConfigurationProperties(prefix = "main.datasource")
    public DataSource mainDataSource() {
        return DataSourceBuilder.create().build();
    }

}

备份数据源:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("org.app")
@EntityScan("org.app")
public class BackupDataSourceConfig {

    @Bean(name = "backupDataSource")
    @ConfigurationProperties(prefix = "backup.datasource")
    public DataSource backupDataSource() {
        return DataSourceBuilder.create().build();
    }

}

谢谢!

1 个答案:

答案 0 :(得分:0)

我弄明白该怎么做。希望这可以帮助任何人:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("org.app")
@EntityScan("org.app")

public class DataSourceConfig {

    private static final String USERNAME = "sa";
    private static final String PASSWORD = "sa";

    @Bean
    @Primary
    public DataSource dataSource() {
        DataSource dataSource;
        try {
            dataSource = getMainDataSource();
            dataSource.getConnection().isValid(500);
        } catch (Exception e) {
            log.error("Main database not valid.", e);
            dataSource =getBackupDataSource();
        }
        return dataSource;
    }

    private DataSource getMainDataSource() {
        return DataSourceBuilder.create()
                .driverClassName("com.mysql.jdbc.Driver")
                .username(USERNAME)
                .password(PASSWORD)
                .url("jdbc:mysql://localhost:3306/app?useSSL=false")
                .build();
    }

    private DataSource getBackupDataSource() {
        return DataSourceBuilder.create()
                .driverClassName("org.h2.Driver")
                .username(USERNAME)
                .password(PASSWORD)
                .url("jdbc:h2:/app;DB_CLOSE_ON_EXIT=FALSE")
                .build();
    }
}

刚上豆。