关于springBoot如何配置双数据源

前言

本文采用springBoot+配置类的方式简单配置Mysql+PostgreSql双数据源。

1.首先导入需要的pom依赖

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>

<!--postgreSql驱动包--->
<dependency>
	<groupId>org.postgresql</groupId>
	<artifactId>postgresql</artifactId>
	<scope>runtime</scope>
</dependency>

<!-- 这里采用 HikariCP连接池-->
<dependency>
<groupId>com.zaxxer</groupId>
	<artifactId>HikariCP</artifactId>
	<version>3.2.0</version>
</dependency>

2.配置yaml文件

#端口
server:
  port: 8080
mybatis:
  #mysql和postgreSql xml文件映射的位置
  mapper-locations: classpath:mysqlMapper/*.xml,classpath:postgreSqlMapper/*.xml
  configuration:
    #开启驼峰命名
    map-underscore-to-camel-case: true
    #日志打印
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3.配置MySQL的配置类

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Qualifier;
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;

@Configuration
@MapperScan(basePackages = "com.wgl.towsources.mysqlMapper",sqlSessionFactoryRef = "mysqlSessionFactory")
public class MysqlConfig {
    @Bean(name = "mysqlDataSource")
    @Primary //声明配置主数据源(注意:这里需要在postgreSql或者mysql当中用该注解声明主数据源,这里采用mysql为主数据源)
    public HikariDataSource dataSource(){
        HikariConfig config = new HikariConfig();
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        config.setJdbcUrl("jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
        config.setUsername("");// 用户名
        config.setPassword("");// 密码
        return new HikariDataSource(config);
    }

    /**
     * 配置mysql事物管理器
     */
    @Bean(name="mysqlTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(){
        return new DataSourceTransactionManager(this.dataSource());
    }

    /**
     * 配置mysql的session工厂
     */
    @Bean(name="mysqlSessionFactory")
    @Primary
    public SqlSessionFactory mySqlSessionFactory(@Qualifier("mysqlDataSource") HikariDataSource mysqlDataSource, MybatisProperties mybatisProperties) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mysqlMapper/*.xml"));
        bean.setDataSource(mysqlDataSource);
        // 双数据源都打印sql需要配置这里
        bean.setConfiguration(mybatisProperties.getConfiguration());
        return bean.getObject();
    }
}

4.配置postgreSql配置类

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = "com.wgl.towsources.postgreSqlMapper",sqlSessionFactoryRef = "postgreSqlSessionFactory")
public class PostgreSqlConfig {

    @Bean(name = "postgreSqlDataSource")
    public HikariDataSource dataSource(){
        HikariConfig config = new HikariConfig();
        config.setDriverClassName("org.postgresql.Driver");
        config.setJdbcUrl("jdbc:postgresql://localhost:5432/postgres");
        config.setUsername("");//用户名
        config.setPassword("");//密码
        return new HikariDataSource(config);
    }

    /**
     * 配置postgreSql事物管理器
     */
    @Bean(name="postgreSqlTransactionManager")
    public DataSourceTransactionManager transactionManager(){
        return new DataSourceTransactionManager(this.dataSource());
    }

    /**
     * 配置postgreSql的session工厂
     */
    @Bean(name="postgreSqlSessionFactory")
    public SqlSessionFactory postgreSqlSessionFactory(@Qualifier("postgreSqlDataSource") HikariDataSource postgreSqlDataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:postgreSqlMapper/*.xml"));
        bean.setDataSource(postgreSqlDataSource);
        return bean.getObject();
    }
}

5.运行项目(打印端口号说明启动成功)

截图

6.接下来写一个controller测试一下

@RestController
public class TestController {

    @Autowired
    private StudentMapper mysqlStudentMapper;

    @Autowired
    private PostgreStudentMapper postgreSqlStudentMapper;

    /**
     * 查询mysql的student表
     * @return
     */
    @GetMapping("/get")
    public List<Student> getForMysql(){
        return mysqlStudentMapper.get();
    }

    /**
     * 查询postgreSql的student表
     * @return
     */
    @GetMapping("/get2")
    public List<com.wgl.towsources.entity.postgreSql.Student> getForPostgreSql(){
        return postgreSqlStudentMapper.get();
    }
}

截图
截图

到此,双数据源就配置成功啦~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值