【基础版】Springboot2.x+Mybatis配置多数据源

网上大多数教程都是比较老的版本(Springboot1.x),很多方法已经因升级而不再被支持,我经过实践,找到了一种比较简单的方案来配置多数据源,基本可以直接放在自己的项目中修改使用。

如何建立Springboot项目等过程我就不赘述了,相信看到这篇文章的你已经熟练掌握,我只写一下配置的方式以及简单的功能实现。

项目的部分pom.xml简单列出来大家参考一下。


    org.springframework.boot
    spring-boot-starter-parent
    2.0.4.RELEASE

	org.mybatis.spring.boot
	mybatis-spring-boot-starter
	1.3.2



	mysql
	mysql-connector-java
	runtime



	com.alibaba
	druid-spring-boot-starter
	1.1.10

我们在application.yml中配置多数据源的基本信息,注意,配置多数据源时不要配置spring.datasource,连接池我用的是阿里的druid,没有的话可以用默认的。

另外,在springboot2.x中配置多数据源时,原来的url部分要用jdbc-url,否则会报错java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.

application.yml配置多数据源

market: # 市场数据库
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        jdbc-url: jdbc:mysql://127.0.0.1:3306/market?useUnicode=true&characterEncoding=UTF-8&useSSL=false
        username: root
        password: 123456
        type: com.alibaba.druid.pool.DruidDataSource
trade: # 交易数据库
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        jdbc-url: jdbc:mysql://127.0.0.1:3306/trade?useUnicode=true&characterEncoding=UTF-8&useSSL=false
        username: root
        password: 123456
        type: com.alibaba.druid.pool.DruidDataSource

完整的application.yml

spring:
    profiles:
        active: dev
    mybatis:
        configuration:
           cache-enabled: false
           map-underscore-to-camel-case: true
           use-generated-keys: true
           default-executor-type: reuse
           default-statement-timeout: 600
    redis:
        database: 0
        host: 127.0.0.1
        port: 6379
        password: 1234
        pool:
            max-active: 8
            max-wait: -1
            max-idle: 8
            min-idle: 0
            timeout: 0
market: # 市场数据库
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        jdbc-url: jdbc:mysql://127.0.0.1:3306/market?useUnicode=true&characterEncoding=UTF-8&useSSL=false
        username: root
        password: 123456
        type: com.alibaba.druid.pool.DruidDataSource
trade: # 交易数据库
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        jdbc-url: jdbc:mysql://127.0.0.1:3306/trade?useUnicode=true&characterEncoding=UTF-8&useSSL=false
        username: root
        password: 123456
        type: com.alibaba.druid.pool.DruidDataSource

接下来是让springboot找到我们的配置,并配置多连接

新建MultipleDBConfig.java(建议放在config包中)

MultipleDBConfig.java

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class MultipleDBConfig {
    @Bean(name = "market")
    @Primary
    @ConfigurationProperties(prefix = "market.datasource")
    public DataSource marketDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "marketJdbcTemplate")
    public JdbcTemplate marketJdbcTemplate(@Qualifier("market") DataSource dsMarket) {
        return new JdbcTemplate(dsMarket);
    }

    @Bean(name = "trade")
    @ConfigurationProperties(prefix = "trade.datasource")
    public DataSource tradeDataSource() {
        return  DataSourceBuilder.create().build();
    }

    @Bean(name = "tradeJdbcTemplate")
    public JdbcTemplate tradeJdbcTemplate(@Qualifier("trade") 
                                              DataSource dsTrade) {
        return new JdbcTemplate(dsTrade);
    }
}

此处要注意,@ConfigurationProperties注解配置的是在application.yml中编辑的数据源信息的前缀,切记,需要在一个数据源加上@Primary注解,否则会提示发现多个数据源而无法启动(如下图)

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method sqlSessionFactory in org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration required a single bean, but 2 were found:
	- market: defined by method 'marketDataSource' in class path resource [com/finanstar/fx/config/MultipleDBConfig.class]
	- trade: defined by method 'tradeDataSource' in class path resource [com/finanstar/fx/config/MultipleDBConfig.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

配置基本到这里就结束了,下面来看一下我们配置后的效果,我们在controller中简单写两个方法来测试一下:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/hello")
public class HelloController {
	
    @Autowired
    @Qualifier("marketJdbcTemplate")
    private JdbcTemplate marketTemplate;

    @Autowired
    @Qualifier("tradeJdbcTemplate")
    private JdbcTemplate tradeTemplate;

    private final static Logger logger = LoggerFactory.getLogger(HelloController.class);
	
    @GetMapping(value = "/getMarketUser")
    public String getPGUser() {
        Map map = new HashMap();
        String query = " select * from user where id='20180903001'";
        try {
            // 每条记录对应一个Map,当只返回一条数据时用queryForMap即可
            map = marketTemplate.queryForMap(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Marke Data: " + map.toString();
    }

    @GetMapping(value = "/getTradeUser")
    public String getMYUser() {
        List> list = new ArrayList>();
        String query = " select * from user";
        try {
            // 如果返回多条数据需要用queryForList方法,并用一个泛型为Map的List来接收
            list = tradeTemplate.queryForList(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Trade Data: " + list.toString();
    }
}

此时启动Springboot项目,在浏览器访问http://{ip}:{port}/hello/getMarketUser或http://{ip}:{port}/hello/getTradeUser即可看到我们的结果。

更多方式请留意后续更新,这次只是一个基础版本,还有更多更加方便的方式来选择,比如通过aop来进行数据源的动态切换等。

你可能感兴趣的:(后端)