我有一个Spring Boot应用程序,需要有一个主要和辅助数据源.当有连接问题时,我需要实现一些关于如何重新连接的逻辑.由于Spring为您提供连接,我似乎无法告诉它在出现问题时重新连接.
我知道如何制作2个数据源,但是当它使用哪一个时,哪里是处理逻辑的最佳位置.逻辑需要以这种方式工作:
在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)