JAVA技术交流QQ群:170933152

1.可以静态配置数据库

2.也可以动态切换数据库

项目提交测试,趁着中当间的这个空档期,把springboot的多数据源配置学习一下,总体来说多数据源配置有两种方式,一种是静态的,一种是动态的。
静态的方式

我们以两套配置方式为例,在项目中有两套配置文件,两套mapper,两套SqlSessionFactory,各自处理各自的业务,这个两套mapper都可以进行增删改查的操作,在这两个主MYSQL后也可以各自配置自己的slave,实现数据的备份。如果在增加一个数据源就得从头到尾的增加一遍。先看看两个配置文件:
## master 数据源配置
master1.datasource.url=jdbc:mysql://localhost:3306/learn?useUnicode=true&characterEncoding=utf8
master1.datasource.username=root
master1.datasource.password=
master1.datasource.driverClassName=com.mysql.jdbc.Driver
 
 
## slave 数据源配置
master2.datasource.url=jdbc:mysql://localhost:3308/learn?useUnicode=true&characterEncoding=utf8
master2.datasource.username=root
master2.datasource.password=
master2.datasource.driverClassName=com.mysql.jdbc.Driver
这两个数据源的配置不分主从,看网上很多这种配置方式,说是主从配置,个人认为既然什么都是两套就没有必要分出主从,分出读写了,根据业务的需求以及数据库服务器的性能进行划分即可。两个配置类
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = Master1DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "master1SqlSessionFactory")
public class Master1DataSourceConfig {
    // 精确到 master 目录,以便跟其他数据源隔离
    static final String PACKAGE = "com.hui.readwrite.mapper.master1";
    static final String MAPPER_LOCATION = "classpath:mapper/master1.xml";
 
    @Value("${master1.datasource.url}")
    private String url;
 
    @Value("${master1.datasource.username}")
    private String user;
 
    @Value("${master1.datasource.password}")
    private String password;
 
    @Value("${master1.datasource.driverClassName}")
    private String driverClass;
 
    @Bean(name = "master1DataSource")
    @Primary
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }
 
    @Bean(name = "master1TransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(masterDataSource());
    }
 
    @Bean(name = "master1SqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("master1DataSource") DataSource masterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(Master1DataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}

@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = Master2DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "master2SqlSessionFactory")
public class Master2DataSourceConfig {
        // 精确到 master 目录,以便跟其他数据源隔离
        static final String PACKAGE = "com.hui.readwrite.mapper.master2";
        static final String MAPPER_LOCATION = "classpath:mapper/master2.xml";
 
        @Value("${master2.datasource.url}")
        private String url;
 
        @Value("${master2.datasource.username}")
        private String user;
 
        @Value("${master2.datasource.password}")
        private String password;
 
        @Value("${master2.datasource.driverClassName}")
        private String driverClass;
 
        @Bean(name = "master2DataSource")
        public DataSource master2DataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(driverClass);
            dataSource.setUrl(url);
            dataSource.setUsername(user);
            dataSource.setPassword(password);
            return dataSource;
        }
 
        @Bean(name = "master2TransactionManager")
        public DataSourceTransactionManager master2TransactionManager() {
            return new DataSourceTransactionManager(master2DataSource());
        }
 
        @Bean(name = "master2SqlSessionFactory")
        public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("master2DataSource") DataSource master2DataSource) throws Exception {
            final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(master2DataSource);
            sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                    .getResources(Master2DataSourceConfig.MAPPER_LOCATION));
            return sessionFactory.getObject();
    }
}

@Primary 标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。「多数据源配置的时候注意,必须要有一个主数据源,用 @Primary 标志该 Bean」
@MapperScan 扫描 Mapper 接口并容器管理,包路径精确到 master,为了和下面 cluster 数据源做到精确区分
@Value 获取全局配置文件 application.properties 的 kv 配置,并自动装配
sqlSessionFactoryRef 表示定义了 key ,表示一个唯一 SqlSessionFactory 实例
两个mapper接口的路径和xml文件的路径如下:

这样就可以实现同一个项目使用多个数据配置,缺点是不易维护和扩展。
动态方式

这种方式实现了一个写库多个读库,使用的是同一套Mapper接口和XML文件,这样就有很好的拓展性,具体代码如下:

先是生成不同的数据源,其中多个读数据源合并
@Configuration
public class DataBaseConfiguration{
 
 
    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;
 
 
    @Bean(name="writeDataSource", destroyMethod = "close", initMethod="init")
    @Primary
    @ConfigurationProperties(prefix = "spring.write.datasource")
    public DataSource writeDataSource() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
    /**
     * 有多少个从库就要配置多少个
     * @return
     */
    @Bean(name = "readDataSourceOne")
    @ConfigurationProperties(prefix = "spring.read.one")
    public DataSource readDataSourceOne(){
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
 
 
    @Bean(name = "readDataSourceTwo")
    @ConfigurationProperties(prefix = "spring.read.two")
    public DataSource readDataSourceTwo() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
 
 
    @Bean("readDataSources")
    public List<DataSource> readDataSources(){
        List<DataSource> dataSources=new ArrayList<DataSource>();
        dataSources.add(readDataSourceOne());
        dataSources.add(readDataSourceTwo());
        return dataSources;
    }
}
生成一套SqlSessionFactory,进行动态切换
@Configuration
@ConditionalOnClass({EnableTransactionManagement.class})
@Import({ DataBaseConfiguration.class})
@MapperScan(basePackages={"com.hui.readwrite.mapper.master1"})
public class TxxsbatisConfiguration {
 
 
    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;
 
 
    @Value("${datasource.readSize}")
    private String dataSourceSize;
 
 
    @Resource(name = "writeDataSource")
    private DataSource dataSource;
 
 
    @Resource(name = "readDataSources")
    private List<DataSource> readDataSources;
 
 
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(roundRobinDataSouceProxy());
        sqlSessionFactoryBean.setTypeAliasesPackage("com.hui.readwrite.po");
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/master1*//*.xml"));
        sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sqlSessionFactoryBean.getObject();
    }
    /**
     * 有多少个数据源就要配置多少个bean
     * @return
     */
    @Bean
    public AbstractRoutingDataSource roundRobinDataSouceProxy() {
        int size = Integer.parseInt(dataSourceSize);
        TxxsAbstractRoutingDataSource proxy = new TxxsAbstractRoutingDataSource(size);
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        targetDataSources.put(DataSourceType.write.getType(),dataSource);
        for (int i = 0; i < size; i++) {
            targetDataSources.put(i, readDataSources.get(i));
        }
        proxy.setDefaultTargetDataSource(dataSource);
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }
}

进行选择,和读库的简单负载。Spring boot提供了AbstractRoutingDataSource根据用户定义的规则选择当前的数据库,这样我们可以在执行查询之前,设置读取从库,在执行完成后,恢复到主库。实现可动态路由的数据源,在每次数据库查询操作前执行
public class TxxsAbstractRoutingDataSource extends AbstractRoutingDataSource {
 
 
    private final int dataSourceNumber;
    private AtomicInteger count = new AtomicInteger(0);
 
 
    public TxxsAbstractRoutingDataSource(int dataSourceNumber) {
        this.dataSourceNumber = dataSourceNumber;
    }
 
 
    @Override
    protected Object determineCurrentLookupKey() {
        String typeKey = DataSourceContextHolder.getJdbcType();
        if (typeKey.equals(DataSourceType.write.getType()))
            return DataSourceType.write.getType();
        // 读 简单负载均衡
        int number = count.getAndAdd(1);
        int lookupKey = number % dataSourceNumber;
        return new Integer(lookupKey);
    }
}

利用AOP的方式实现,方法的控制
@Aspect
@Component
public class DataSourceAop {
 
 
    public static final Logger logger = LoggerFactory.getLogger(DataSourceAop.class);
 
 
    @Before("execution(* com.hui.readwrite.mapper..*.select*(..)) || execution(* com.hui.readwrite.mapper..*.get*(..))")
    public void setReadDataSourceType() {
        DataSourceContextHolder.read();
        logger.info("dataSource切换到:Read");
    }
 
 
    @Before("execution(* com.hui.readwrite.mapper..*.insert*(..)) || execution(* com.hui.readwrite.mapper..*.update*(..))")
    public void setWriteDataSourceType() {
        DataSourceContextHolder.write();
        logger.info("dataSource切换到:write");
    }
}
配置文件:

#一些总的配置文件
spring.aop.auto=true
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
datasource.readSize=2
 
# 主数据源,默认的
spring.write.datasource.driverClassName=com.mysql.jdbc.Driver
spring.write.datasource.url=jdbc:mysql://localhost:3306/learn?useUnicode=true&characterEncoding=utf8
spring.write.datasource.username=root
spring.write.datasource.password=root
 
# 从数据源
spring.read.one.driverClassName=com.mysql.jdbc.Driver
spring.read.one.url=jdbc:mysql://localhost:3307/learn?useUnicode=true&characterEncoding=utf8
spring.read.one.username=root
spring.read.one.password=root
 
 
spring.read.two.driverClassName=com.mysql.jdbc.Driver
spring.read.two.url=jdbc:mysql://localhost:3308/learn?useUnicode=true&characterEncoding=utf8
spring.read.two.username=root
spring.read.two.password=root

我们可以看到效果:

关于事务的观点

核心思想,spring提供了一个DataSource的子类,该类支持多个数据源
org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource
上述静态多个数据库的这种配置是不支持分布式事务的,也就是同一个事务中,不能操作多个数据库。
一些实时性要求很高的select语句,我们也可能需要放到master上执行,这些查询可能也需要放在master上执行,而不能放在slave上去执行,因为slave上可能存在延时。
如果有多台 master 或者有多台 slave。多台master组成一个HA,要实现当其中一台master挂了是,自动切换到另一台master,这个功能可以使用LVS/Keepalived来实现,也可以通过进一步扩展ThreadLocalRountingDataSource来实现,可以另外加一个线程专门来每个一秒来测试mysql是否正常来实现。同样对于多台slave之间要实现负载均衡,同时当一台slave挂了时,要实现将其从负载均衡中去除掉,这个功能既可以使用LVS/Keepalived来实现,同样也可以通过近一步扩展ThreadLocalRountingDataSource来实现。
因为事务是依赖数据源的,你用注解切换数据源的操作 跟 用注解加事务控制的操作应该是注意下先后关系。切换数据源的注解配置是要放在事务注解配置前面的,不然有问题。
解决方案添加分布式的事务,Atomikos和spring结合来处理。
配置多个不同的数据源,使用一个sessionFactory,在业务逻辑使用的时候自动切换到不同的数据源,有一个种是在拦截器里面根据不同的业务现切换到不同的datasource;有的会在业务层根据业务来自动切换。但这种方案在多线程并发的时候会出现一些问题,需要使用threadlocal等技术来实现多线程竞争切换数据源的问题。
由于我使用的注解式事务,和我们的AOP数据源切面有一个顺序的关系。数据源切换必须先执行,数据库事务才能获取到正确的数据源。所以要明确指定 注解式事务和 我们AOP数据源切面的先后顺序。我们数据源切换的AOP是通过注解来实现的,只需要在AOP类上加上一个order(1)注解即可,其中1代表顺序号。

spring的事务管理,是基于数据源的,所以如果要实现动态数据源切换,而且在同一个数据源中保证事务是起作用的话,就需要注意二者的顺序问题,即:在事物起作用之前就要把数据源切换回来。
举一个例子:web开发常见是三层结构:controller、service、dao。一般事务都会在service层添加,如果使用spring的声明式事物管理,在调用service层代码之前,spring会通过aop的方式动态添加事务控制代码,所以如果要想保证事物是有效的,那么就必须在spring添加事务之前把数据源动态切换过来,也就是动态切换数据源的aop要至少在service上添加,而且要在spring声明式事物aop之前添加.根据上面分析:
最简单的方式是把动态切换数据源的aop加到controller层,这样在controller层里面就可以确定下来数据源了。不过,这样有一个缺点就是,每一个controller绑定了一个数据源,不灵活。对于这种:一个请求,需要使用两个以上数据源中的数据完成的业务时,就无法实现了。
针对上面的这种问题,可以考虑把动态切换数据源的aop放到service层,但要注意一定要在事务aop之前来完成。这样,对于一个需要多个数据源数据的请求,我们只需要在controller里面注入多个service实现即可。但这种做法的问题在于,controller层里面会涉及到一些不必要的业务代码,例如:合并两个数据源中的list…
此外,针对上面的问题,还可以再考虑一种方案,就是把事务控制到dao层,然后在service层里面动态切换数据源。
源码地址

感谢:

http://www.itwendao.com/article/detail/210530.html
http://www.jianshu.com/p/8813ec02926a
http://blog.csdn.net/dream_broken/article/details/72851329

SpringCloud学习笔记027---SpringBoot集成MyBatis_实现多数据源_可以自定义数据库类型相关推荐

  1. SpringCloud学习笔记022---SpringBoot中集成使用MongoDb进行增删改查

    1.首先在Windows上安装Mongodb,当然也可以在centos上安装   我是在windows上安装的   安装的时候使用一些命令,开启服务   可以看另一篇博文:   安装后访问:http: ...

  2. SpringCloud学习笔记015---Spring Boot集成RabbitMQ发送接收JSON

    在Spring Boot 集成RabbitMQ一文中介绍了如何集成RabbitMQ.默认情况下发送的消息是转换为字节码,这里介绍一下如何发送JSON数据. ObjectMapper 最简单发送JSON ...

  3. 分布式系统服务注册与发现原理 SpringCloud 学习笔记

    分布式系统服务注册与发现原理 & SpringCloud 学习笔记 分布式系统服务注册与发现原理 引入服务注册与发现组件的原因 单体架构 应用与数据分离 集群部署 微服务架构 架构演进总结 服 ...

  4. SpringCloud 学习笔记(1 / 3)

    Spring Cloud 学习笔记(2 / 3) Spring Cloud 学习笔记(3 / 3) 文章目录 01\_前言闲聊和课程说明 02\_零基础微服务架构理论入门 03\_第二季Boot和Cl ...

  5. SpringCloud学习笔记(1)- Spring Cloud Netflix

    文章目录 SpringCloud学习笔记(1)- Spring Cloud Netflix 单体应用存在的问题 Spring Cloud Eureka Eureka Server代码实现 Eureka ...

  6. SpringCloud 学习笔记

    SpringCloud 学习笔记 最开始新建一个新的maven项目,什么都不选,直接写名字就好,这里是 springloud 新建后,把 src 目录删除,在pom.xml文件导入依赖 <!-- ...

  7. SpringBoot学习笔记(4)----SpringBoot中freemarker、thymeleaf的使用

    1. freemarker引擎的使用 如果你使用的是idea或者eclipse中安装了sts插件,那么在新建项目时就可以直接指定试图模板 如图: 勾选freeMarker,此时springboot项目 ...

  8. SpringCloud学习笔记(1)- Spring Cloud Alibaba

    文章目录 SpringCloud学习笔记(1)- Spring Cloud Alibaba 服务治理 Nacos 服务注册 Nacos 服务发现与调用 Ribbon 负载均衡 Sentinel 服务限 ...

  9. Spring-Cloud 学习笔记-(4)负载均衡器Ribbon

    目录 Spring-Cloud 学习笔记-(4)负载均衡器Ribbon 1.前言 2.什么是负载均衡 2.1.问题分析 2.2.什么是Ribbon 3.快速入门 3.1.实现方式一 3.1.1.修改代 ...

最新文章

  1. Post和Get方法区别
  2. 5个无聊透顶的 Python 程序
  3. python 格式化时间
  4. left join 临时表_不懂SQL优化?那你就OUT了——表连接的优化
  5. 鸿蒙系统董事长,鸿蒙2.0已开源 华为轮值董事长:今年至少3亿设备搭载鸿蒙系统...
  6. 使用React和Spring Boot构建一个简单的CRUD应用
  7. python lib库_python_lib基础库
  8. MapReduce程序之数据排序
  9. 【hortonworks/registry】registry 如何创建 互相依赖的 schema
  10. VMware下载(官网)
  11. 计算机安全模式怎么消除计,大神为你解说win7系统解除word安全模式的妙计
  12. 基于NanoPi3(三星S5P6818)的kernel移植(二)
  13. fiddler限速_基于fiddler来模拟限速
  14. 使用jupyter环境在数据集处理中遇到.ipynb_checkpoints no such file or directory的问题
  15. 微信创建公众号菜单时出现48001,api unauthorized rid怎么解决?
  16. linux脚本:每天晚上 12 点,打包站点目录/var/www/html 备份到/data 目录下
  17. 从突变到新抗原:肿瘤与免疫系统之间的一场豪赌!
  18. vivox27怎么去掉信息红点_还记得五彩斑斓的黑?vivo X27 Pro获红点奖
  19. 高德地图定位及导航开发流程
  20. maven 本地仓库配置

热门文章

  1. centos7.5 supervisor +nginx 开机启动设置(实测最有效)以及出现问题思路
  2. linux下安装opencv4.4.0
  3. Qt 串口通信 高速发送出错的解决方法总结
  4. (轉貼) C Standard Library (初級) (C/C++)
  5. centos 6.5 x64 上安装mariadb10
  6. 第二届大数据世界论坛 聚焦行业需求
  7. 详细认识一下CSS盒子模型
  8. 网络监控工具--ntop
  9. 三月提示:提防挂马网站 关注账号安全
  10. 最真挚的祝福最深的伤