SpringBoot支持mybatis与mysql多数据源配置实战

一、背景:

有访问量的项目,数据库分领域隔离是比较明智的选择,万一后续流量上来,应用层扩容或者业务拆分,相对于数据层面的拆分,会简单很多。

用springBoot约定大于配置,但是涉及复杂的配置,往往力不从心,没有掌控感。此文目的是让有需要的同学可以step-by-step的去配置,避免走弯路,之前看到很多文章质量不佳,一旦实操,各种错误,令人崩溃,springBoot入门简单,但是理解他的约定还是有门槛的。

二、实验环境:

springBoot  2.1.1 + mybatis + mysql-8.4.0 + druid -1.1.17(连接池管理)+ jdk1.8

三、相关配置及代码

整体思路:本地mysql创建两个库,各有一张表,配置多数据源进行访问,最后写个UT进行验证。

整体代码结构如下:

1、pom.xml配置mybatis及mysql、druid等的相关依赖
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.0</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.47</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.10</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.17</version>
		</dependency>
2、创建数据库及表结构

在本地弄两个库(user, order_info),库里面各创建一张表

--创建用户库及表
create database user;
use user;
CREATE TABLE student(
    id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(255) DEFAULT NULL,
    age int(11) DEFAULT NULL,
    PRIMARY KEY(id)
)ENGINE=InnODB DEFAULT CHARSET=utf8;


create database order_info;
use order_info;
--订单表,用于测试mybatis多数据配置正确性验证
CREATE TABLE order_master (
	order_id bigint(20) NOT NULL AUTO_INCREMENT comment '订单id',
  	order_no char(12) NOT NULL comment '订单号,唯一',
	buyer_id bigint(20) NOT NULL comment '买家ID',
	seller_id bigint(20) not null comment '商家ID',
	status tinyint(2) not null comment '状态:0-已下单,1-已发货,2-已收货,3-订单退货',
	order_amount decimal(15,2) default null comment '订单金额',
	pay_status tinyint(2) not null default 0 comment '支付状态:0-未支付,1-已支付',
	pay_time datetime  DEFAULT null  comment '支付时间',
	create_time datetime  DEFAULT NOW() comment '创建时间',
  	PRIMARY KEY (order_id),
  	unique(order_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
3.配置数据源相关信息及mybatis访问目录

这里要特别注意,网上很多资料,都是在类似数据源user-db下面还配置“druid:" 节点,在下面配置了数据库连接池,实践证明会出现(No suitable driver found for xxx 或者 Failed to determine a suitable driver class)的错误。

spring:
  datasource:
      user-db:
        driver-class-name: com.mysql.jdbc.Driver # 数据库驱动
        url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false&zeroDateTimeBehavior=convertToNull  # url
        username: root # 账号
        password: root123 # 密码
        type: com.alibaba.druid.pool.DruidDataSource # 数据源类型,这里指定为Druid数据源
        # DataSource DruidDataSource连接池的基本配置信息
        #初始化连接池的连接数量 大小,最小,最大
        initial-size: 5
        min-idle: 5
        max-active: 20
        #配置获取连接等待超时的时间
        max-wait: 60000
        #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        time-between-eviction-runs-millis: 60000
        # 配置一个连接在池中最小生存的时间,单位是毫秒
        min-evictable-idle-time-millis: 30000
        validation-query: SELECT 1 FROM DUAL
        test-while-idle: true
        test-on-borrow: true
        test-on-return: false
        # 是否缓存preparedStatement,也就是PSCache  官方建议MySQL下建议关闭   个人建议如果想用SQL防火墙 建议打开
        pool-prepared-statements: false
        max-pool-prepared-statement-per-connection-size: 20
        # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        filter:
           stat:
              merge-sql: true
              slow-sql-millis: 5000
      order-db:
        driver-class-name: com.mysql.jdbc.Driver # 数据库驱动
        url: jdbc:mysql://localhost:3306/order_info??useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false&zeroDateTimeBehavior=convertToNull  # url
        username: root # 账号
        password: root123 # 密码
        type: com.alibaba.druid.pool.DruidDataSource # 数据源类型,这里指定为Druid数据源
        # DataSource DruidDataSource连接池的基本配置信息
        #初始化连接池的连接数量 大小,最小,最大
        initial-size: 5
        min-idle: 5
        max-active: 20
        #配置获取连接等待超时的时间
        max-wait: 60000
      
  • 30
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用 Spring Boot 配置多个 MyBatis 数据源的示例代码: 首先,我们需要在 `application.properties` 文件中配置多个数据源的相关信息: ```properties # 配置第一个数据源 spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1 spring.datasource.primary.username=username1 spring.datasource.primary.password=password1 spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver # 配置第二个数据源 spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2 spring.datasource.secondary.username=username2 spring.datasource.secondary.password=password2 spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver ``` 接下来,我们需要创建多个数据源的 `DataSource` 对象,并将其注入到 `SqlSessionFactory` 中: ```java @Configuration @MapperScan(basePackages = "com.example.mapper", sqlSessionTemplateRef = "primarySqlSessionTemplate") public class PrimaryDataSourceConfig { @Bean @Primary @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @Primary public SqlSessionFactory primarySqlSessionFactory() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(primaryDataSource()); return factoryBean.getObject(); } @Bean @Primary public SqlSessionTemplate primarySqlSessionTemplate() throws Exception { return new SqlSessionTemplate(primarySqlSessionFactory()); } } @Configuration @MapperScan(basePackages = "com.example.mapper", sqlSessionTemplateRef = "secondarySqlSessionTemplate") public class SecondaryDataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactory secondarySqlSessionFactory() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(secondaryDataSource()); return factoryBean.getObject(); } @Bean public SqlSessionTemplate secondarySqlSessionTemplate() throws Exception { return new SqlSessionTemplate(secondarySqlSessionFactory()); } } ``` 这里我们使用 `@MapperScan` 注解扫描 `com.example.mapper` 包下的所有 Mapper 接口,并使用 `sqlSessionTemplateRef` 属性指定使用哪个 `SqlSessionTemplate`。 最后,在 Mapper 接口中使用 `@Qualifier` 注解指定使用哪个数据源: ```java @Mapper @Qualifier("primarySqlSessionTemplate") public interface PrimaryMapper { // ... } @Mapper @Qualifier("secondarySqlSessionTemplate") public interface SecondaryMapper { // ... } ``` 以上就是使用 Spring Boot 配置多个 MyBatis 数据源的示例代码,希望能对你有所帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值