Spring Boot-重新启动后重新连接到数据库

问题描述 投票:0回答:1

我有一个Spring Batch应用程序,它每10分钟运行一次。它从REST API获取一些数据,然后将这些数据保存在数据库中。

好,我现在的问题在哪里?

有时数据库(Oracle)可能会重新启动或脱机(实际上不知道)。但是应用程序似乎没有重新连接到数据库。它只是处于空闲模式。

Spring Boot:2.1.2.RELEASE

application.yml看起来像这样:

app:
  database:
    jdbc-url: jdbc:oracle:thin:@<host>:<port>:<db>
    username: <username>
    password: <password>
    driver-class-name: oracle.jdbc.OracleDriver
    options:
      show-sql: true
      ddl-auto: none
      dialect: org.hibernate.dialect.Oracle12cDialect

然后,我像这样配置数据源:

    public DataSource dataSource() {
        HikariConfig configuration = new HikariConfig();

        configuration.setJdbcUrl(properties.getJdbcUrl());
        configuration.setUsername(properties.getUsername());
        configuration.setPassword(properties.getPassword());
        configuration.setDriverClassName(properties.getDriverClassName());
        configuration.setLeakDetectionThreshold(60 * 1000);

        return new HikariDataSource(configuration);
    }

    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);

        em.setPackagesToScan("xxx.xxx.xx");
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        Properties additionalProperties = properties();
        em.setJpaProperties(additionalProperties);

        return em;
    }

    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }

    private Properties properties() {
        Properties additionalProperties = new Properties();
        additionalProperties.setProperty("hibernate.hbm2ddl.auto", properties.getOptions().getDdlAuto());
        additionalProperties.setProperty("hibernate.dialect", properties.getOptions().getDialect());
        additionalProperties.setProperty("hibernate.show_sql", properties.getOptions().getShowSql());
        return additionalProperties;
    }

老实说,我不确定我是否在配置中做错了任何事情。

谢谢!

oracle hibernate spring-boot spring-batch hikaricp
1个回答
0
投票

您应通过maxLifetime配置setMaxLifetime 30分钟

 configuration.setMaxLifetime(108000);

属性控制池中连接的最大生存期。 当连接达到此超时时,即使最近使用过,它也会从池中退回。一个正在使用的连接将永远不会停止,只有当它处于空闲状态时,它才会被删除。

我们强烈建议设置此值,它至少应比任何数据库或基础结构施加的连接时间限制少30秒。

默认情况下,Oracle不强制连接的最长生存期

© www.soinside.com 2019 - 2024. All rights reserved.