小编Mat*_*t H的帖子

Spring Boot中的主/辅助故障转移DataSource

我有一个Spring Boot应用程序,需要有一个主要和辅助数据源.当有连接问题时,我需要实现一些关于如何重新连接的逻辑.由于Spring为您提供连接,我似乎无法告诉它在出现问题时重新连接.

我知道如何制作2个数据源,但是当它使用哪一个时,哪里是处理逻辑的最佳位置.逻辑需要以这种方式工作:

  1. 连接到主要
  2. 如果存在连接问题,则资源不可用或发生连接超时,请尝试重新连接到主服务器.
  3. 如果主节点无法连接,请尝试连接到辅助节点
  4. 如果辅助节点无法连接,请继续重试步骤2和3,持续X分钟.

在Spring Service中处理这个问题是否最好/可能?我应该有一个不同的服务,只处理这个逻辑,我的其他服务使用它吗?不连接到DB的"弹簧方式"并使用"普通的旧Java方式"会更好吗?

以下是我所拥有的服务仅连接到主服务器的示例.

DatasourcesConfig

package com.helloworld.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import oracle.jdbc.pool.OracleDataSource;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class DatasourcesConfig {

    @Primary
    @Bean(name = "primaryDataSource")
    DataSource primaryDataSource() throws SQLException {

        OracleDataSource dataSource = new OracleDataSource();

        dataSource.setUser("user");
        dataSource.setPassword("pass");
        dataSource.setURL("jdbc:oracle:thin:@(...primary connection...)");

        return dataSource;
    }

      @Bean(name = "secondaryDataSource")
      DataSource secondaryDataSource() throws SQLException {

          OracleDataSource dataSource = new OracleDataSource();

          dataSource.setUser("user");
          dataSource.setPassword("pass");
          dataSource.setURL("jdbc:oracle:thin:@(...secondary connection...)");

          return dataSource;
      }

    @Bean(name …
Run Code Online (Sandbox Code Playgroud)

spring spring-boot

13
推荐指数
1
解决办法
3841
查看次数

标签 统计

spring ×1

spring-boot ×1