Spring Boot 集成 Mybatis 实现 Druid 多数据源

今天,日月在这里教大家怎么简洁的使用 Spring Boot 集成 Mybatis 实现 Druid 多数据源,也是经过网上很多示例的参考和实践后整理出来的,献给有需要的猿友们。。。

我们还是延用之前SpringBoot 集成 mybatis的四种方式的项目进行改造

1、pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

<!-- mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

<!-- mysql -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<!-- druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>${druid.version}</version>
</dependency>

2、配置文件application.properties

master 数据源配置

master.datasource.url=jdbc:mysql://localhost:3306/test1?useSSL=false&useUnicode=true&characterEncoding=utf8
master.datasource.username=root
master.datasource.password=123456
master.datasource.maxActive=50
master.datasource.maxWait=60000
master.datasource.driverClassName=com.mysql.jdbc.Driver

cluster 数据源配置

cluster.datasource.url=jdbc:mysql://localhost:3306/test2?useSSL=false&useUnicode=true&characterEncoding=utf8
cluster.datasource.username=root
cluster.datasource.password=123456
cluster.datasource.maxActive=50
cluster.datasource.maxWait=60000
cluster.datasource.driverClassName=com.mysql.jdbc.Driver

3、多数据源配置
主数据源

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = MasterDataSourceConfiguration.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfiguration {
    // 精确到 master 目录,以便跟其他数据源隔离
    static final String PACKAGE = "com.chenqi.springboot.dao.master";
    static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml";
    @Value("${master.datasource.url}")
    private String url;
    @Value("${master.datasource.username}")
    private String user;
    @Value("${master.datasource.password}")
    private String password;
    
    @Value("${master.datasource.maxActive}")
    private Integer maxActive;
    
    @Value("${master.datasource.maxWait}")
    private Integer maxWait;
    @Value("${master.datasource.driverClassName}")
    private String driverClass;
    @Bean(name = "dataSource")
    @Primary
    public DruidDataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setMaxActive(maxActive);
        dataSource.setMaxWait(maxWait);
        return dataSource;
    }
    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(masterDataSource());
    }
    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("dataSource") DruidDataSource masterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MasterDataSourceConfiguration.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}

注意主数据源要加@Primary注解,并且beanname一定要是 dataSource

从数据源

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;

@Configuration
//扫描 Mapper 接口并容器管理
@MapperScan(basePackages = ClusterDataSourceConfiguration.PACKAGE, sqlSessionFactoryRef = "clusterSqlSessionFactory")
public class ClusterDataSourceConfiguration {
// 精确到 cluster 目录,以便跟其他数据源隔离
static final String PACKAGE = "com.chenqi.springboot.dao.cluster";
static final String MAPPER_LOCATION = "classpath:mapper/cluster/*.xml";

@Value("${cluster.datasource.url}")
private String url;

@Value("${cluster.datasource.username}")
private String user;

@Value("${cluster.datasource.password}")
private String password;
@Value("${cluster.datasource.maxActive}")
private Integer maxActive;
@Value("${cluster.datasource.maxWait}")
private Integer maxWait;

@Value("${cluster.datasource.driverClassName}")
private String driverClass;

@Bean(name = "clusterDataSource")
public DruidDataSource clusterDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setMaxActive(maxActive);
dataSource.setMaxWait(maxWait);
return dataSource;
}

@Bean(name = "clusterTransactionManager")
public DataSourceTransactionManager clusterTransactionManager() {
return new DataSourceTransactionManager(clusterDataSource());
}

@Bean(name = "clusterSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DruidDataSource clusterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(clusterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(ClusterDataSourceConfiguration.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}

4、serviceImpl

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.chenqi.springboot.dao.cluster.ClusterMapper;
import com.chenqi.springboot.dao.master.MasterMapper;
import com.chenqi.springboot.service.TestService;
@Service
public class TestServiceImpl implements TestService {
    
    @Autowired
    MasterMapper masterMapper;
    
    @Autowired
    ClusterMapper clusterMapper;
    @Override
    public String test() {
        return masterMapper.test() + "---" + clusterMapper.test();
    }
}

其他就没有什么改动了,根据各数据源中配置的dao路径和xml路径写各自的代码即可。数据库我们还是延用上一章中的test1(master)和test2(cluster)数据库(注意mapper中切记不要加@mapper)

OK了,我们启动项目,访问http://localhost:8080/hello
返回:
在这里插入图片描述
至此,说明,多数据源的配置测试成功。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值