Spring Boot Двойная конфигурация данных, невозможно восстановить соединение после потери соединения - PullRequest
0 голосов
/ 14 декабря 2018

Все.Я работаю над приложением, написанным весной Boot 1.5.3.У меня есть два источника данных, которые настроены как показано ниже.

Основное соединение

spring.datasource.driverClassName = org.postgresql.Driver
spring.datasource.url = jdbc:postgresql://xxx.xxx.xxx.xx:5432/mydb
spring.datasource.username = xxxx
spring.datasource.password = xxxx

spring.jpa.properties.hibernate.default_schema=test
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.tomcat.max-wait=10000
# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=150
spring.datasource.tomcat.max-idle=30
spring.datasource.tomcat.min-idle=2
spring.datasource.tomcat.initial-size=3
# Validate the connection before borrowing it from the pool.
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.test-on-connect=true
spring.datasource.time-between-eviction-runs-millis=60000
#spring.datasource.tomcat.validation-query-timeout=1000
spring.datasource.tomcat.validation-query=SELECT 1
spring.datasource.tomcat.validation-interval=1000
spring.datasource.tomcat.remove-abandoned=true
spring.datasource.tomcat.remove-abandoned-timeout=55
spring.datasource.tomcat.test-while-idle=true
spring.datasource.tomcat.min-evictable-idle-time-millis = 55000
spring.datasource.tomcat.time-between-eviction-runs-millis = 34000

Второе соединение

 spring.rdatasource.driverClassName = org.postgresql.Driver
    spring.rdatasource.url = jdbc:postgresql://xxx.xxx.xxx.xx:5432/mydb1
    spring.rdatasource.username = xxxx
    spring.rdatasource.password = xxxx

    spring.jpa.properties.hibernate.default_schema=test
    # Number of ms to wait before throwing an exception if no connection is available.
    spring.rdatasource.tomcat.max-wait=10000
    # Maximum number of active connections that can be allocated from this pool at the same time.
    spring.rdatasource.tomcat.max-active=150
    spring.rdatasource.tomcat.max-idle=30
    spring.rdatasource.tomcat.min-idle=2
    spring.rdatasource.tomcat.initial-size=3
    # Validate the connection before borrowing it from the pool.
    spring.rdatasource.tomcat.test-on-borrow=true
    spring.rdatasource.tomcat.test-on-connect=true
    spring.rdatasource.time-between-eviction-runs-millis=60000
    #spring.rdatasource.tomcat.validation-query-timeout=1000
    spring.rdatasource.tomcat.validation-query=SELECT 1
    spring.rdatasource.tomcat.validation-interval=1000
    spring.rdatasource.tomcat.remove-abandoned=true
    spring.rdatasource.tomcat.remove-abandoned-timeout=55
    spring.rdatasource.tomcat.test-while-idle=true
    spring.rdatasource.tomcat.min-evictable-idle-time-millis = 55000
    spring.rdatasource.tomcat.time-between-eviction-runs-millis = 34000

Я работаю в среде VPN.Когда я запускаю приложение, приложение работает нормально.Но проблема начинается, когда я отключаю VPN и снова подключаю VPN.again, мое приложение не будет повторно подключаться к источнику данных снова.Вместо этого я всегда получаю исключение.

Но работаю с единой базой данных, когда покидаю обработку соединения, и сам не выполняю настройку базы данных.

Пожалуйста, помогите мне.Я предоставлю любую другую информацию, которая потребуется.

Обновление

@Configuration
@PropertySource({ "classpath:application.properties" })
@EnableJpaRepositories(
    basePackages = {"com.services.persistence"}, 
    entityManagerFactoryRef = "entityManager", 
    transactionManagerRef = "transactionManager"
)
@ComponentScan("com.services.persistence")
@EnableTransactionManagement
public class DBConfig {

    @Autowired private Environment env;

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManager() {
        LocalContainerEntityManagerFactoryBean em
          = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(userDataSource());
        em.setPackagesToScan(
          new String[] { "com.services.persistence", "com.services.persistence.pojo" });

        HibernateJpaVendorAdapter vendorAdapter
          = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
//        properties.put("hibernate.hbm2ddl.auto",
//          env.getProperty("hibernate.hbm2ddl.auto"));
        properties.put("hibernate.dialect",
          env.getProperty("spring.jpa.database-platform"));
        properties.put("hibernate.current_session_context_class",
                env.getProperty("spring.jpa.properties.hibernate.current_session_context_class"));

        em.setJpaPropertyMap(properties);

        return em;
    }

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

    @Primary
    @Bean
    public JpaTransactionManager transactionManager() {

        JpaTransactionManager transactionManager
          = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
          entityManager().getObject());
        return transactionManager;
    }

    @Bean(name = "sessionFactory")
    public SessionFactory getSessionFactory() {
      SessionFactory sessionFactory = transactionManager().getEntityManagerFactory().unwrap(SessionFactory.class);

        if (sessionFactory == null) {
            throw new NullPointerException("factory is not a hibernate factory");
        } else {
            System.out.println(
                    "==================================== Transaction Enabled ========================================");
            return sessionFactory;
        }
    }

Я также настроил spring.rdatasource, и он такой же, как файл выше, за исключением того, что он не установлен в качестве основного и других дополнительных деталей, таких как pojo, менеджер транзакций и т. д.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...