Spring Druid多数据源配置

六眼飞鱼酱① 提交于 2019-12-06 16:42:09

SpringBoot 多数据源配置

如果需要在一个应用中使用多个数据源,应当如何实现呢,在Spring配置MyBatis中,我们可以看到以下的代码

<!-- mybatis 的SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" scope="prototype">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>

MyBatis的一个SqlSession即代表了一个数据源的配置,所以要实现多个数据源的,配置多个不同的SqlSession就行

依赖引入

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
    </dependencies>

依赖中引入了mybatis,mysql驱动和druid连接池

配置SqlSession

首先在应用配置文件中添加数据源的相关配置

spring:
  datasource:
    druid:
      # 数据库访问配置, 使用druid数据源
      # 数据源1 mysql
      mysql1:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC
        username: root
        password: ranger
      # 数据源2 oracle
      mysql2:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC
        username: root
        password: ranger

在这里配置了两个数据源

然后分别配置两个SqlSession

    /**
     * @Author ranger
     * @Date 2019/12/5 23:47
     * MySQL1数据源配置
     **/
    
    @Configuration
    @MapperScan(basePackages = "com.ranger.datasource.mysqlDao", sqlSessionFactoryRef = "mysqlSqlSessionFactory")
    public class MySQLSqlSessionConfig {
    
        @Primary
        @Bean(name = "mysqldatasource")
        @ConfigurationProperties("spring.datasource.druid.mysql1")
        public DataSource mysqlDataSource() {
            return DruidDataSourceBuilder.create().build();
        }
    
        @Bean(name = "mysqlTransactionManager")
        @Primary
        public DataSourceTransactionManager mysqlTransactionManager() {
            return new DataSourceTransactionManager(mysqlDataSource());
        }
    
        @Bean(name = "mysqlSqlSessionFactory")
        @Primary
        public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqldatasource") DataSource dataSource)
                throws Exception {
            final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            //如果不使用xml的方式配置mapper,则可以省去下面这行mapper location的配置。
    //        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
    //                .getResources("classpath:mapper/mysql/*.xml"));
            return sessionFactory.getObject();
        }
    }


/**
 * @Author ranger
 * @Date 2019/12/5 23:53
 * MySQL2数据源配置
 **/

@Configuration
@MapperScan(basePackages = "com.ranger.datasource.otherDao", sqlSessionFactoryRef = "otherSqlSessionFactory")
public class OtherSqlSessionConfig {
    @Bean(name = "otherdatasource")
    @ConfigurationProperties("spring.datasource.druid.mysql2")
    public DataSource mysqlDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "otherTransactionManager")
    public DataSourceTransactionManager mysqlTransactionManager() {
        return new DataSourceTransactionManager(mysqlDataSource());
    }

    @Bean(name = "otherSqlSessionFactory")
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("otherdatasource") DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        //如果不使用xml的方式配置mapper,则可以省去下面这行mapper location的配置。
//        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
//                .getResources("classpath:mapper/other/*.xml"));
        return sessionFactory.getObject();
    }
}

两个数据源分别配置了不同的Mapper路径

测试

创建一个User实体和UserController来测试数据源是否可以正常使用

@Controller
@RequestMapping("user")
public class UserController {

    // 引入MySQL的配置
    @Autowired
    private MysqlUserDao mysqlUserDao;

    @Autowired
    private OtherUserDao otherUserDao;

    @ResponseBody
    @RequestMapping("all/mysql")
    public List<User> getAll(){
        return mysqlUserDao.selectAll();
    }

    @ResponseBody
    @RequestMapping("all/other")
    public List<User> getAllOther(){
        return otherUserDao.selectAll();
    }
}

浏览器访问http://localhost:8080/user/all/mysqlhttp://localhost:8080/user/all/other可以看到不同的返回结果

mysql数据源.png

other数据源.png

这样就实现了多数据源,不同的Dao使用不同的数据源

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!