温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springboot中怎么实现多数据源的动态切换

发布时间:2021-07-08 17:09:32 来源:亿速云 阅读:183 作者:Leah 栏目:编程语言

这篇文章给大家介绍springboot中怎么实现多数据源的动态切换,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1、maven依赖

<!--数据库连接--><dependency>      <groupId>com.oracle</groupId>      <artifactId>ojdbc6</artifactId>      <version>11.2.0.4</version>      <scope>runtime</scope>    </dependency><!--数据库连接池-><dependency>      <groupId>com.alibaba</groupId>      <artifactId>druid-spring-boot-starter</artifactId>      <version>1.1.10</version>    </dependency>    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-jdbc</artifactId>    </dependency><!--aop-><dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-aop</artifactId>    </dependency>

2、多数据源信息配置

#多数据源测试spring: datasource:  druid:   master:    driver-class-name: oracle.jdbc.driver.OracleDriver    username: test    password: test    url: jdbc:oracle:thin:@//ip1:1521/orcl   slave:    driver-class-name: oracle.jdbc.driver.OracleDriver    username: test    password: test    url: jdbc:oracle:thin:@//ip2:1521/orcl

3、数据源配置信息转换成实体类

@ConfigurationProperties(prefix = "spring.datasource.druid")@Data@Componentpublic class DataSourceProperties {  private Map<String,String>master;  private Map<String,String>slave;}

4、动态数据源切换类

public class DynamicDataSource extends AbstractRoutingDataSource {  private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();  public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {    super.setDefaultTargetDataSource(defaultTargetDataSource);    super.setTargetDataSources(targetDataSources);    super.afterPropertiesSet();  }  @Override  protected Object determineCurrentLookupKey() {    return getDataSource();  }  public static void setDataSource(String dataSource) {    contextHolder.set(dataSource);  }  public static String getDataSource() {    return contextHolder.get();  }  public static void clearDataSource() {    contextHolder.remove();  }}

5、多数据源配置类

@Configurationpublic class DynamicDataSourceConfig {  @Bean  public DataSource master(@Autowired DataSourceProperties dataSourceProperties){    DruidDataSource druidDataSource = new DruidDataSource();    Map<String, String> master = dataSourceProperties.getMaster();    druidDataSource.setUsername(master.get("username"));    druidDataSource.setPassword(master.get("password"));    druidDataSource.setUrl(master.get("url"));    //其他参数配置 省略    return druidDataSource;  }  @Bean  public DataSource slave(@Autowired DataSourceProperties dataSourceProperties){    DruidDataSource druidDataSource = new DruidDataSource();    Map<String, String> slave = dataSourceProperties.getSlave();    druidDataSource.setUsername(slave.get("username"));    druidDataSource.setPassword(slave.get("password"));    druidDataSource.setUrl(slave.get("url"));    //其他参数配置 省略    return druidDataSource;  }  @Bean  @Primary  public DynamicDataSource dataSource(DataSource master,DataSource slave){    Map<Object,Object>map = new HashMap<>(4);    map.put("master",master);    map.put("slave",slave);    return new DynamicDataSource(master,map);  }}

6、自定义@DataSource注解

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface DataSource {  String name() default "master";}

7、Aop切面类配置

@Component@Aspectpublic class DataSourceAspect {  @Pointcut("@annotation(com.zxgeo.sso.muiltDatasource.anons.DataSource)")  public void dataSourcePointCut(){}  @Around(value = "dataSourcePointCut()")  public Object around(ProceedingJoinPoint point) throws Throwable {    MethodSignature signature = (MethodSignature) point.getSignature();    Method method = signature.getMethod();    DataSource dataSource = method.getAnnotation(DataSource.class);    if(dataSource == null){      DynamicDataSource.setDataSource("master");    }else {      DynamicDataSource.setDataSource(dataSource.name());    }    try {      return point.proceed();    } finally {      DynamicDataSource.clearDataSource();    }  }}

8、启动配置注解信息,重要(不然运行会报错)

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})

9、测试

(1)、service层(此处没有使用mybatis)

@Servicepublic class TestService {  @Autowired  private javax.sql.DataSource dataSource;  @DataSource  public Map<String,Object> getMasterDataSource() throws SQLException {    Connection connection = dataSource.getConnection();    Map<String,Object> map;    try (PreparedStatement preparedStatement           = connection.prepareStatement("SELECT * FROM AA WHERE A=10001")) {      ResultSet resultSet = preparedStatement.executeQuery();      map = new HashMap<>();      while (resultSet.next()){        map.put("A",resultSet.getString("A"));        map.put("B",resultSet.getString("B"));        map.put("C",resultSet.getString("C"));      }    }    return map;  }  @DataSource(name = "slave")  public Map<String,Object> getSlaveDataSource() throws SQLException {    Connection connection = dataSource.getConnection();    Map<String,Object> map;    try (PreparedStatement preparedStatement           = connection.prepareStatement("SELECT * FROM AA WHERE A=10002")) {      ResultSet resultSet = preparedStatement.executeQuery();      map = new HashMap<>();      while (resultSet.next()){        map.put("A",resultSet.getString("A"));        map.put("B",resultSet.getString("B"));        map.put("C",resultSet.getString("C"));      }    }    return map;  }}

(2)、单元测试

@SpringBootTest@RunWith(SpringRunner.class)class SsoApplicationTests {  @Autowired  private TestService testService;  @Test  public void muliDatasorce() throws SQLException {    Map<String, Object> masterDataSourceUrl = testService.getMasterDataSource();    System.out.println(masterDataSourceUrl);    Map<String, Object> slaveDataSourceUrl = testService.getSlaveDataSource();    System.out.println(slaveDataSourceUrl);  }}

关于springboot中怎么实现多数据源的动态切换就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI