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

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

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

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

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
</parent>
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.2</version>
</dependency>

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

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-starter</artifactId>
	<version>1.1.10</version>
</dependency>

我们在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<String, Object> map = new HashMap<String, Object>();
        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<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        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/getMarketUserhttp://{ip}:{port}/hello/getTradeUser即可看到我们的结果。

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
图书简介<br>本书分为6大部分,其中第一部分为Spring概述性知识;第二部分讲解了Spring框架核心技术的内容;第三部分涵盖了在Spring中使用各种数据访问技术的内容;第四部分讲解业务层各种技术的知识;第五部分是展现层技术的知识;第六部分讲解了如何测试Spring应用和Spring各种工具类的知识。 全书深刻揭示了Spring的技术内幕,对IoC、AOP、事务管理等根基性的技术进行了深度的挖掘。读者阅读本书后,不但可以熟练使用Spring的各项功能,对各种Spring内部机制也将了然于胸,真正做到知其然知其所以然。此外,我们还对Spring技术所涉及到的各种Java技术、Java设计模式进行了适时的介绍,通过这些背景知识的准备,读者在理解Spring的各项原理时将不会有任何的障碍。 <br>========================================================================<br><br>第1篇 概述<br>第1章 Spring概述<br>第2章 快速入门<br>第2篇 Spring核心技术<br>第3章 IoC容器概述<br>第4章 在IoC容器中装配Bean<br>第5章 Spring容器高级主题<br>第6章 Spring AOP基础<br>第7章 基于@AspectJ和Schema的<br>第7章 AOP<br>第3篇 数据库访问<br>第8章 Spring对DAO的支持<br>第9章 Spring的事务管理<br>第10章 使用Spring JDBC访问数据库<br>第11章 使用JPA访问数据库<br>第12章 整合其他ORM框架<br>第4篇 业务层应用<br>第13章 任务调度和异步执行器<br>第14章 JavaMail发送邮件<br>第15章 在Spring中使用JMS<br>第16章 在Spring中开发Web Service<br>第17章 使用Acegi实施应用系统安全<br>第18章 动态语言支持<br>第5篇 展现层应用<br>第19章 Spring MVC之一<br>第20章 Spring MVC之二<br>第21章 集成其他Web框架<br>第6篇 其他<br>第22章 Spring应用的测试<br>第23章 Spring工具类盘点<br>附录A 各种数据库连接配置及驱动<br>附录B IDE开发环境设置 <br>=================================================<br>注意:全书章节过大,分为3部分上传。请下载其余两部分。<br>Apple祝您学习Spring愉快。<br>老规矩:有分的的给评分,每分的给顶一下。免费发放<br>

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值