• 动态切换数据源总结学习


            要实现动态数据源切换,离不开Spring框架的AbstractRoutingDataSource这个抽象类。这是实现动态数据源切换的关键。我们先看下这个抽象类。

            AbstractRoutingDataSource的源码如下:

    1. //
    2. // Source code recreated from a .class file by IntelliJ IDEA
    3. // (powered by Fernflower decompiler)
    4. //
    5. package org.springframework.jdbc.datasource.lookup;
    6. import java.sql.Connection;
    7. import java.sql.SQLException;
    8. import java.util.Collections;
    9. import java.util.Map;
    10. import javax.sql.DataSource;
    11. import org.springframework.beans.factory.InitializingBean;
    12. import org.springframework.jdbc.datasource.AbstractDataSource;
    13. import org.springframework.lang.Nullable;
    14. import org.springframework.util.Assert;
    15. import org.springframework.util.CollectionUtils;
    16. public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
    17. @Nullable
    18. private Map targetDataSources;
    19. @Nullable
    20. private Object defaultTargetDataSource;
    21. private boolean lenientFallback = true;
    22. private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
    23. @Nullable
    24. private Map resolvedDataSources;
    25. @Nullable
    26. private DataSource resolvedDefaultDataSource;
    27. public AbstractRoutingDataSource() {
    28. }
    29. public void setTargetDataSources(Map targetDataSources) {
    30. this.targetDataSources = targetDataSources;
    31. }
    32. public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
    33. this.defaultTargetDataSource = defaultTargetDataSource;
    34. }
    35. public void setLenientFallback(boolean lenientFallback) {
    36. this.lenientFallback = lenientFallback;
    37. }
    38. public void setDataSourceLookup(@Nullable DataSourceLookup dataSourceLookup) {
    39. this.dataSourceLookup = (DataSourceLookup)(dataSourceLookup != null ? dataSourceLookup : new JndiDataSourceLookup());
    40. }
    41. public void afterPropertiesSet() {
    42. if (this.targetDataSources == null) {
    43. throw new IllegalArgumentException("Property 'targetDataSources' is required");
    44. } else {
    45. this.resolvedDataSources = CollectionUtils.newHashMap(this.targetDataSources.size());
    46. this.targetDataSources.forEach((key, value) -> {
    47. Object lookupKey = this.resolveSpecifiedLookupKey(key);
    48. DataSource dataSource = this.resolveSpecifiedDataSource(value);
    49. this.resolvedDataSources.put(lookupKey, dataSource);
    50. });
    51. if (this.defaultTargetDataSource != null) {
    52. this.resolvedDefaultDataSource = this.resolveSpecifiedDataSource(this.defaultTargetDataSource);
    53. }
    54. }
    55. }
    56. protected Object resolveSpecifiedLookupKey(Object lookupKey) {
    57. return lookupKey;
    58. }
    59. protected DataSource resolveSpecifiedDataSource(Object dataSource) throws IllegalArgumentException {
    60. if (dataSource instanceof DataSource) {
    61. return (DataSource)dataSource;
    62. } else if (dataSource instanceof String) {
    63. return this.dataSourceLookup.getDataSource((String)dataSource);
    64. } else {
    65. throw new IllegalArgumentException("Illegal data source value - only [javax.sql.DataSource] and String supported: " + dataSource);
    66. }
    67. }
    68. public Map getResolvedDataSources() {
    69. Assert.state(this.resolvedDataSources != null, "DataSources not resolved yet - call afterPropertiesSet");
    70. return Collections.unmodifiableMap(this.resolvedDataSources);
    71. }
    72. @Nullable
    73. public DataSource getResolvedDefaultDataSource() {
    74. return this.resolvedDefaultDataSource;
    75. }
    76. public Connection getConnection() throws SQLException {
    77. return this.determineTargetDataSource().getConnection();
    78. }
    79. public Connection getConnection(String username, String password) throws SQLException {
    80. return this.determineTargetDataSource().getConnection(username, password);
    81. }
    82. public T unwrap(Class iface) throws SQLException {
    83. return iface.isInstance(this) ? this : this.determineTargetDataSource().unwrap(iface);
    84. }
    85. public boolean isWrapperFor(Class iface) throws SQLException {
    86. return iface.isInstance(this) || this.determineTargetDataSource().isWrapperFor(iface);
    87. }
    88. protected DataSource determineTargetDataSource() {
    89. Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
    90. Object lookupKey = this.determineCurrentLookupKey();
    91. DataSource dataSource = (DataSource)this.resolvedDataSources.get(lookupKey);
    92. if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
    93. dataSource = this.resolvedDefaultDataSource;
    94. }
    95. if (dataSource == null) {
    96. throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
    97. } else {
    98. return dataSource;
    99. }
    100. }
    101. @Nullable
    102. protected abstract Object determineCurrentLookupKey();
    103. }

            首先,这个类AbstractRoutingDataSource这个抽象类是继承了AbstractDataSource抽象类,并且实现了InitializingBean接口。InitializingBean接口提供了一个afterPropertiesSet()方法,凡是继承了该接口的类那么在初始化Bean的时候就会执行该方法。所以AbstractRoutingDataSource类中的afterPropertiesSet正是用于初始化一些信息。要想了解InitializingBean这个接口,可以参考我的这篇blog:Spring框架中InitializingBean的作用 

            其次,这个类AbstractRoutingDataSource类有个抽象方法,这个抽象方法需要我们实现,这个方法的作用就是指定用哪个数据源,也就是告诉dao层现在连接数据源用我们指定的数据源了。

                    

    protected abstract Object determineCurrentLookupKey();

            AbstractRoutingDataSource还继承了抽象类AbstractDataSource,而AbstractDataSource抽象类又继承了DataSource接口,在DataSource中只有两个方法,这两个方法会在AbstractDataSource抽象类中得到具体实现。
            

            现在看看AbstractRoutingDataSource中的一些属性都有什么作用

    1. @Nullable
    2. private Map targetDataSources; 目标数据源,也就是我们要切换的多个数据源都存放到这里
    3. @Nullable
    4. private Object defaultTargetDataSource; 默认数据源,如果想指定默认数据源,可以给它赋值
    5. private boolean lenientFallback = true;
    6. private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
    7. @Nullable
    8. private Map resolvedDataSources;存放真正的数据源信息,将targetDataSources的信息copy一份
    9. @Nullable
    10. private DataSource resolvedDefaultDataSource; 默认数据源,将defaultTargetDataSource转为DataSource赋值给resolvedDefaultDataSource
    11. public AbstractRoutingDataSource() {
    12. }

               AbstractRoutingDataSource抽象类中afterPropertiesSet()方法是核心,那看看他到底做了哪些初始化操作。

            

    1. public void afterPropertiesSet() {
    2. if (this.targetDataSources == null) {
    3. throw new IllegalArgumentException("Property 'targetDataSources' is required");
    4. } else {
    5. this.resolvedDataSources = CollectionUtils.newHashMap(this.targetDataSources.size());
    6. this.targetDataSources.forEach((key, value) -> {
    7. Object lookupKey = this.resolveSpecifiedLookupKey(key);
    8. DataSource dataSource = this.resolveSpecifiedDataSource(value);
    9. this.resolvedDataSources.put(lookupKey, dataSource);
    10. });
    11. if (this.defaultTargetDataSource != null) {
    12. this.resolvedDefaultDataSource = this.resolveSpecifiedDataSource(this.defaultTargetDataSource);
    13. }
    14. }
    15. }

            第一,当targetDataSources为空时,会抛出IllegalArgumentException错误,所以我们在配置多数据源时,至少需要传入一个数据源。

            第二, 初始化了resolvedDataSources大小,resolvedDataSources只是把targetDataSources的内容copy了一份,不同之处在于targetDataSources的value是Object类型,而resolvedDataSources的value是DataSource类型。
            第三,遍历targetDataSources集合,然后调用了resolveSpecifiedLookupKey()方法和resolveSpecifiedDataSource()方法,最后将返回值当作Key-Value放入resolvedDataSources集合中。

            第四,那么方法resolveSpecifiedLookupKey()和方法resolveSpecifiedDataSource()分别做了什么呢?我们可以查看两个方法的实现。其实可以看到resolveSpecifiedLookupKey并没有做什么操作就直接返回了值,而resolveSpecifiedDataSource只是把Object转为DataSource对象返回。
            

            所以afterPropertiesSet()初始话就是将targetDataSources的内容转化一下放到resolvedDataSources中,将defaultTargetDataSource转为DataSource赋值给resolvedDefaultDataSource

            我们再看getConnection()方法是如何实现的。调用了determineTargetDataSource()方法

            

    1. public Connection getConnection() throws SQLException {
    2. return this.determineTargetDataSource().getConnection();
    3. }

            那么determineTargetDataSource方法到底做了什么,我们可以看一下determineTargetDataSource的实现。该方法返回DataSource类型的对象,并且调用了determineCurrentLookupKey方法,可能这时有人发现了这个方法就是我们自定义数据源类要实现的那个方法。determineCurrentLookupKey返回一个Object,命名为lookupKey,将lookupKey作为key,到resolvedDataSources集合中去拿数据源,如果没有拿到数据源,那么它会拿默认数据源resolvedDefaultDataSource。如果还是没有拿到,此时就报错啦!

            通过上面的分析,我们自己实现的方法determineCurrentLookupKey()是什么时候别调用的呢?从逻辑上看determineCurrentLookupKey()被determineTargetDataSource()调用,而determineTargetDataSource()被getConnection()调用,那getConnection()方法是被谁在什么时候调用的呢?通过代码跟踪,是我们在service层调用dao层方法时,这时候调用的。

            

            了解了AbstractRoutingDataSource这个抽象类,也就该实现一个动态数据源切换功能了,涉及的源码如下:

            

    1. package com.lsl.mylsl.config;
    2. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
    3. /**
    4. * 动态数据源实现类
    5. */
    6. public class DynamicDataSource extends AbstractRoutingDataSource {
    7. @Override
    8. protected Object determineCurrentLookupKey() {
    9. String dataSource = DBContextHolder.getDataSource();
    10. if (dataSource == null || "".equals(dataSource)){
    11. dataSource = "ds1";
    12. }
    13. return dataSource;
    14. }
    15. }

            当没有指定数据源时,默认指定ds1为当前数据源

            

    1. package com.lsl.mylsl.config;
    2. public class DBContextHolder {
    3. private static final ThreadLocal CONTEXT_HOLDER = new ThreadLocal<>();
    4. /**
    5. * 动态切换数据源
    6. * @param dataSource
    7. */
    8. public static void setDataSource(String dataSource){
    9. if (SpringbootConfig.DBMAP.containsKey(dataSource)){
    10. CONTEXT_HOLDER.set(dataSource);
    11. }else {
    12. System.out.println("数据源" + dataSource + "不存在");
    13. }
    14. }
    15. /**
    16. * 获取数据源
    17. * @return
    18. */
    19. public static String getDataSource(){
    20. return CONTEXT_HOLDER.get();
    21. }
    22. /**
    23. * 清空数据源
    24. */
    25. public static void clearDataSource(){
    26. CONTEXT_HOLDER.remove();
    27. }
    28. }

            

            

    1. package com.lsl.mylsl.config;
    2. import com.alibaba.druid.pool.DruidDataSource;
    3. import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
    4. import org.springframework.context.annotation.Bean;
    5. import org.springframework.context.annotation.Configuration;
    6. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    7. import org.springframework.transaction.PlatformTransactionManager;
    8. import javax.sql.DataSource;
    9. import java.util.HashMap;
    10. import java.util.Map;
    11. /**
    12. * 初始化多个数据源
    13. * 注册动态数据源
    14. */
    15. @Configuration
    16. public class SpringbootConfig {
    17. public static final Map DBMAP = new HashMap<>();
    18. /**
    19. * 初始化数据源1
    20. */
    21. public void initDataSource1(){
    22. try {
    23. DruidDataSource dds1 = DruidDataSourceBuilder.create().build();
    24. dds1.setUsername("admin");
    25. dds1.setPassword("123456");
    26. dds1.setUrl("jdbc:oracle:thin:@10.10.10.10:1521/oracle1");
    27. dds1.setInitialSize(5);
    28. dds1.setMinIdle(5);
    29. dds1.setMaxActive(20);
    30. dds1.setMaxWait(60000);
    31. dds1.setTimeBetweenEvictionRunsMillis(60000);
    32. dds1.setMinEvictableIdleTimeMillis(300000);
    33. dds1.setValidationQuery("SELECT * FROM DUAL");
    34. dds1.setTestWhileIdle(true);
    35. dds1.setTestOnBorrow(false);
    36. dds1.setTestOnReturn(false);
    37. dds1.setMaxPoolPreparedStatementPerConnectionSize(20);
    38. dds1.setFilters("stat,wall");
    39. dds1.setConnectionProperties("druid.stat.mergeSql=true;druid.stat.slow.slowSqlMillis=5000");
    40. dds1.setUseGlobalDataSourceStat(true);
    41. //添加数据源到map
    42. SpringbootConfig.DBMAP.put("ds1",dds1);
    43. } catch (Exception e) {
    44. }
    45. }
    46. /**
    47. * 初始化数据源2
    48. */
    49. public void initDataSource2(){
    50. try {
    51. DruidDataSource dds2 = DruidDataSourceBuilder.create().build();
    52. dds2.setUsername("admin");
    53. dds2.setPassword("123456");
    54. dds2.setUrl("jdbc:mysql://10.10.10.10:1521/mysql1");
    55. dds2.setInitialSize(5);
    56. dds2.setMinIdle(5);
    57. dds2.setMaxActive(20);
    58. dds2.setMaxWait(60000);
    59. dds2.setTimeBetweenEvictionRunsMillis(60000);
    60. dds2.setMinEvictableIdleTimeMillis(300000);
    61. dds2.setValidationQuery("SELECT 1");
    62. dds2.setTestWhileIdle(true);
    63. dds2.setTestOnBorrow(false);
    64. dds2.setTestOnReturn(false);
    65. dds2.setMaxPoolPreparedStatementPerConnectionSize(20);
    66. dds2.setFilters("stat,wall");
    67. dds2.setConnectionProperties("druid.stat.mergeSql=true;druid.stat.slow.slowSqlMillis=5000");
    68. dds2.setUseGlobalDataSourceStat(true);
    69. dds2.setDbType("mysql");
    70. //添加数据源到map
    71. SpringbootConfig.DBMAP.put("ds2",dds2);
    72. } catch (Exception e) {
    73. }
    74. }
    75. /**
    76. * 把DynamicDataSource交给spring托管
    77. * @return
    78. */
    79. @Bean
    80. public DataSource dynamicDataSource(){
    81. DynamicDataSource myDs = new DynamicDataSource();
    82. initDataSource1();
    83. initDataSource2();
    84. myDs.setTargetDataSources(SpringbootConfig.DBMAP);
    85. myDs.afterPropertiesSet();
    86. return myDs;
    87. }
    88. /**
    89. * 事务管理
    90. * @return
    91. */
    92. @Bean
    93. public PlatformTransactionManager transactionManager(){
    94. return new DataSourceTransactionManager(dynamicDataSource());
    95. }
    96. }

            如何实现数据源切换,代码很简单,如下:

    1. package com.lsl.mylsl.service.impl;
    2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    3. import com.lsl.mylsl.BO.CatBO;
    4. import com.lsl.mylsl.config.DBContextHolder;
    5. import com.lsl.mylsl.mapper.CatMapper;
    6. import com.lsl.mylsl.service.ICatService;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.stereotype.Service;
    9. import java.util.List;
    10. import java.util.Map;
    11. @Service
    12. public class CatServiceImpl extends ServiceImpl implements ICatService {
    13. @Autowired
    14. CatMapper catMapper;
    15. @Override
    16. public List qryCatByAge(Map params) {
    17. //切换数据源到ds2
    18. DBContextHolder.setDataSource("ds2");
    19. return catMapper.qryCatByAge(params);
    20. }
    21. }

  • 相关阅读:
    【mmdetection代码解读 3.x版本】FPN层的解读
    学生HTML个人网页作业作品 HTML+CSS校园环保(大学生环保网页设计与实现)
    oracle高级
    深入剖析:HTML页面从用户请求到完整呈现的多阶段加载与渲染全流程详解
    详解C语言—预处理
    CorelDRAW Graphics Suite2022免费图形设计软件
    【Linux】项目自动化构建工具——make/Makefile及拓展
    Nginx 配置Nextjs和SpringBoot项目的https并解决跨域问题
    4款.NET开源的Redis客户端驱动库
    44.【list链表的简单属性】
  • 原文地址:https://blog.csdn.net/dhklsl/article/details/127671314