Spring boot 多数据源

Stella981
• 阅读 481

网上多是基于XML文件,本文使用基于配置类的方式使用动态数据源。

多数据源原理

Spring作为项目的应用容器,也对多数据源提供了很好的支持,当我们的持久化框架需要数据库连接时,我们需要做到动态的切换数据源,这些Spring的AbstractRoutingDataSource都给我们留了拓展的空间,可以先来看看抽象类AbstractRoutingDataSource在获取数据库连接时做了什么。

//从配置文件读取到的DataSources的Map
private Map<Object, DataSource> resolvedDataSources; 

//默认数据源
private DataSource resolvedDefaultDataSource;
  
public Connection getConnection() throws SQLException {
   return determineTargetDataSource().getConnection();
}
 
public Connection getConnection(String username, String password) throws SQLException {
   return determineTargetDataSource().getConnection(username, password);
}
  
protected DataSource determineTargetDataSource() {
   Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
   Object lookupKey = determineCurrentLookupKey();
   DataSource dataSource = this.resolvedDataSources.get(lookupKey);
   if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
      dataSource = this.resolvedDefaultDataSource;
   }
   if (dataSource == null) {
      throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
   }
   return dataSource;
}
  
protected abstract Object determineCurrentLookupKey();

可以看到AbstractRoutingDataSource在决定目标数据源的时候,会先调用determineCurrentLookupKey()方法得到一个key,我们通过这个key从配置好的resolvedDataSources(Map结构)拿到这次调用对应的数据源,而determineCurrentLookupKey()开放出来让我们实现。

简单实现AbstractRoutingDataSource

基于上述分析,继承抽象类AbstractRoutingDataSource,并实现determineCurrentLookupKey()方法。

public class MyDataSource extends AbstractRoutingDataSource {
 
    private static final ThreadLocal<String> dataSourceKey = new ThreadLocal<String>();
 
    public static void setDataSourceKey(String dataSource) {
        dataSourceKey.set(dataSource);
    }
 
    protected Object determineCurrentLookupKey() {
        String dsName = dataSourceKey.get();
        //这里需要注意的时,每次我们返回当前数据源的值得时候都需要移除ThreadLocal的值,
        //这是为了避免同一线程上一次方法调用对之后调用的影响
        dataSourceKey.remove(); 
        return dsName;
    }
 
}

实际项目中与mybatis的结合

  1. 配置AbstractRoutingDataSource
  2. 使用AbstractRoutingDataSource作为SqlSessionFactory的数据源
  3. 在使用具体的dao层的相关方法前,设置指定的datasource,动态切换数据源
  4. 执行dao方法的时候就会使用该数据源执行。 ### 配置datasource 说明:默认使用druid连接池。

application.yml中配置Spring数据库连接相关属性。

Springboot 默认会自动加载classpath下的application.ymlapplication.properties文件。
问题:当两个文件同时使用,会同时加载吗?出现冲突会优先选择哪个文件的?
两种文件同时使用时都会加载,如果两文件出现相同的属性名,则application.properties中的会为最终值(测试过。)。

多数据源配置:

datasource:
  type: com.alibaba.druid.pool.DruidDataSource.class
  write:
    name: pushopt
    url: jdbc:mysql://127.0.0.1:3306/pushopt
    username: root
    password: hgfgood
    driver-class-name: com.mysql.jdbc.Driver
    max-active: 20
    initial-size: 1
    max-wait: 6000
    pool-prepared-statements: true
    max-open-prepared-statements: 20
  read1:
    name: test
    url: jdbc:mysql://127.0.0.1:3306/test
    username: root
    password: hgfgood
    driver-class-name: com.mysql.jdbc.Driver
    max-active: 20
    initial-size: 1
    max-wait: 6000
    pool-prepared-statements: true
    max-open-prepared-statements: 20

生成DataSource Bean:

package com.meituan.service.web.opt.config;

import com.meituan.service.web.opt.enums.DataSourceType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hgf on 16/7/29.
 */
@Configuration
public class DataSourceConfiguration {

    private Class<? extends DataSource> datasourceType = com.alibaba.druid.pool.DruidDataSource.class;

    @Bean(name = "writeDataSource")
    @ConfigurationProperties(prefix = "datasource.write")
    public DataSource writeDataSource() {
        return DataSourceBuilder.create().type(datasourceType).build();
    }

    @Bean(name = "readDataSource1")
    @ConfigurationProperties(prefix = "datasource.read1")
    public DataSource readDataSource1() {
        return DataSourceBuilder.create().type(datasourceType).build();
    }

    /**
     * 有多少个数据源就要配置多少个bean
     *
     * @return
     */
    @Bean
    @Primary
    @DependsOn({"writeDataSource", "readDataSource1"})
    public DynamicDataSource dynamicDataSource() {
        DynamicDataSource proxy = new DynamicDataSource();

        //表示可用的数据源,包括写和读数据源
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        // 写
        targetDataSources.put(DataSourceType.WRITE.getType(), writeDataSource());

        //如果有多个DataSource,需要设置多个
        targetDataSources.put(DataSourceType.READ.getType(), readDataSource1());

        //设置默认的数据源为写数据源
        proxy.setDefaultTargetDataSource(writeDataSource());
        proxy.setTargetDataSources(targetDataSources);

        return proxy;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactorys() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
        sqlSessionFactoryBean.setTypeAliasesPackage("com.meituan.service.web.opt.model");

        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources("classpath:/mapper/*.xml"));

        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
        return sqlSessionFactory;
    }

    @Bean
    DataSourceTransactionManager dataSourceTransactionManager() {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dynamicDataSource());
        return dataSourceTransactionManager;
    }

}

注:此处有两个坑,其一是配置DataSource的时候有坑,在实例化AbstractRoutingDataSource的时候不要在属性上设置@Autowired注入,直接使用属性注入或者调用Bean的配置函数否则会产生循环依赖。
正确使用方法:

  @Bean(name = "dynamicDataSource")
  public AbstractRoutingDataSource dynamicDataSource(@Qualifier("writeDataSource") DataSource writeDataSource, @Qualifier("readDataSource1") DataSource readDataSource1) {
      //self defined AbstractRoutingDataSource
      DynamicDataSource proxy = new DynamicDataSource();
      ...
      return proxy;
  }

错误方法:

  @Autowired
  @Qualifier("writeDataSource")
  DataSource writeDataSource;
  @Autowired
  @Qualifier("readDataSource1")
  DataSource readDataSource1;
  @Bean(name = "dynamicDataSource")
  public AbstractRoutingDataSource dynamicDataSource() {
      DynamicDataSource proxy = new DynamicDataSource();
      ...
      return proxy;
  }

错误异常:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'mybatisConfiguration': Unsatisfied dependency expressed through field 'writeDataSource':
Error creating bean with name 'writeDataSource' defined in class path resource [com/meituan/service/web/opt/config/DataSourceConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSourceInitializer': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dynamicDataSource' defined in class path resource [com/meituan/service/web/opt/config/MybatisConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource]: Circular reference involving containing bean 'mybatisConfiguration' - consider declaring the factory method as static for independence from its containing instance. Factory method 'dynamicDataSource' threw exception; nested exception is java.lang.IllegalArgumentException: [Assertion failed] - this argument is required; it must not be null; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'writeDataSource' defined in class path resource [com/meituan/service/web/opt/config/DataSourceConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSourceInitializer': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dynamicDataSource' defined in class path resource [com/meituan/service/web/opt/config/MybatisConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource]: Circular reference involving containing bean 'mybatisConfiguration' - consider declaring the factory method as static for independence from its containing instance. Factory method 'dynamicDataSource' threw exception; nested exception is java.lang.IllegalArgumentException: [Assertion failed] - this argument is required; it must not be null

主要意思就是:mybatisConfigurationbean需要先注入writeDataSourceBean,该Bean依赖dataSourceInitializer,而dataSourceInitializer依赖dynamicDataSource,此时dynamicDataSource由于依赖writeDataSource而没有初始化,所以依赖注入writeDataSource此时没有正确的生成bean,而是null。所以造成初始化Bean失败。

其二就是需要自定义Bean加载顺序。由于DataSource使用DataSourceBuilder创建,该类依赖datasource实例,所以容易产生循环依赖,特别是在先加载DynamicDataSource,的同时加载writeDataSource时。解决方法:使用Spring提供的@DependsOn注解,注解DynamicDataSource。当加载DynamicDataSource,会等待加载writeDataSource,等writeDataSource加载完成后,再加载DynamicDataSource。就不会出现DynamicDataSource->DatasourceInitlizer->writeDataSource->DataSourceInitlizer循环依赖了。

注: 当spring容器中有多个datasource时,使用[@Primary](https://my.oschina.net/primary)决定当有同类别的beans时,如何选择注入那个类。

多数据源集成mybatis

生成AbstractRoutingDataSource的Bean后,使用该Bean配置SqlSessionFactory,就能使动态数据源生效。

注:如果手动配置SqlSessionFactoryBean,那么Spring boot默认会从Ioc容器中选择一个(一般是最先生成的Datasource Bean)DataSource注入到默认的自动加载的SqlSessionFactory中,此时动态数据源不能生效。

自定义SqlSessionFactory,使用SqlSessionFactoryBean来生成SqlSessionFactory

    @Bean
    public SqlSessionFactory sqlSessionFactorys(AbstractRoutingDataSource dynamicDataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //设置mybatis的配置文件路径
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        //设置数据源为动态数据源
        sqlSessionFactoryBean.setDataSource(dynamicDataSource);
        //设置类型前缀包名,在mapper文件中就不用使用详细的包名了,直接使用类名。
        sqlSessionFactoryBean.setTypeAliasesPackage("com.meituan.service.web.opt.model");

        //配置路径匹配器,获取匹配的文件
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources("classpath:/mapper/*.xml"));

        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
        return sqlSessionFactory;
    }

多源数据源是无法跨声明式事务的,一般事务是针对某个DBMS的,需要实现跨DBMS的事务需要使用JTA。

参考

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
浩浩 浩浩
3年前
【Flutter实战】图片和Icon
3.5图片及ICON3.5.1图片Flutter中,我们可以通过Image组件来加载并显示图片,Image的数据源可以是asset、文件、内存以及网络。ImageProviderImageProvider是一个抽象类,主要定义了图片数据获取的接口load(),从不同的数据源获取图片需要实现不同的ImageProvi
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这