springboot+mybatis实现多数据源的访问

springboot +mybatis实现多数据源的访问

单数据源的访问就不说了,这里假设已经实现了springboot+mybatis的单数据源访问流程,下面介绍一下在已经可以访问单数据源的基础上访问多数据源。

1.准备工作

1.1 oracle数据库

1.2 mysql数据库

1.3 已经实现springboot+mybatis对oracle数据库的访问

如果是已经实现springboot+mybatis对mysql数据库的访问也是同理的。

2.新建包和类

在项目中目录src/main/java下cn.idatatech.folivora(这个是自己的包)下新建一个包名为common的包,在该包下新建一个类,类名为DataSourceConfig.java;
DataSourceConfig.java

package cn.idatatech.folivora.common.config;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import cn.idatatech.folivora.common.util.DatabaseUtils;
import cn.idatatech.folivora.modules.test.mapper.EmployeeMapper;

/**
 * 
 * @author zoul [lang.zou]  
 * @date  2018-08-08 15:30:48
 */
@Configuration
@DependsOn({ "databaseUtils", "beanUtils" })
public class DataSourceConfig {

    /**
     * 定义MySql数据源
     * @reurn DataSource
     * @throws Exception
     * @author zoul [lang.zou]  
     * @date  2018-08-08 15:23:53
     */
    @Bean(name = "getDataSourceOfMySql")
    public DataSource getDataSourceOfMySql() throws Exception {
        String url = "jdbc:mysql://localhost:3306/practice";
        String param = "useUnicode=true&characterEncoding=UTF-8&autoReconnect=true";
        String username = "root";
        String password = "123456";
        Map<Object, Object>druidProperties=new HashMap<Object, Object>();
        druidProperties.put("driver-class-name", "com.mysql.jdbc.Driver");
        druidProperties.put("validation-query", "SELECT 1 FROM dual");
        druidProperties.put("test-while-idle", true);
        druidProperties.put("test-on-borrow", true);
        druidProperties.put("test-on-return", true);
        return DatabaseUtils.getDataSource("getDataSourceOfMySql", url + "?" + param, username, password,druidProperties);
    }

    /**
     * 给需要替换成mysql数据库的mapper绑定数据源
     * 这样要这个mapper中的方法要访问数据库的话就会通过mysql配置去访问mysql而不是orcale
     * @return EmployeeMapper
     * @author zoul [lang.zou]  
     * @date  2018-08-08 15:33:48
     */
    @Bean(name = "employeeMapper")
    public EmployeeMapper bindDataSourceToEmployeeMapper() throws Exception {
        DataSource dataSource = this.getDataSourceOfMySql();
        return DatabaseUtils.getMapperOfDataSource(dataSource, EmployeeMapper.class);
    }   
}

注意:我们要把新创建的包放在框架配置能够扫描到的包下,一般放在框架的共同包名开始分支处。
配置完成,注意替换代码中的数据库配置设置和自己的mapper类名称。运行项目,当需要通过上面配置的那个mapper类里面的方法来获取数据时就会从你在上面配置的mysql数据库里面访问数据了。
说明:
上面只是写了一个如何替换数据源配置的类以及绑定需要替换数据源的mapper映射类。其他的结构按正常的springboot+mybatis的架构搭建。即上面相关的
EmployeeController.java
EmployeeService.java
EmployeeMapper.java
EmployeeMapper.xml
都按照单数据源的方法创建好,创建好后在添加一个替换数据源的类即DataSourceConfig.java即可。spring会通过注解的方式把原来的数据源给替换掉。
当然,你在创建时建议先使用单数据源的方式创建好整个流程,确保访问单数据源成功后再通过以上方法替换数据源,以防在写代码过程中出错。

猜你喜欢

转载自blog.csdn.net/qq_23967965/article/details/81510517