springboot + mybatis + Sharding-JDBC实现读写分离

一、引入maven依赖,具体版本大家可根据自己实际需要选择,我这边使用的是4.0.0-RC1版本

<dependency>
  <groupId>org.apache.shardingsphere</groupId>
  <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
  <version>${sharding-sphere.version}</version>
</dependency>

二、application.yml文件配置

server:
  port: 8080
  servlet:
    context-path: /sys
spring:
  main:
    #解决一个实体类无法对应两张表,做一个覆盖操作
    allow-bean-definition-overriding: true
  shardingsphere:
    datasource:
      names:
        master,slave
      # 主数据源
      master:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://xxx:3306/test?autoReconnect=true&useCompression=true&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=GMT
        username: xxxx
        password: xxxx
      # 从数据源
      slave:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://xxxx:3306/test?autoReconnect=true&useCompression=true&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=GMT
        username: xxxx
        password: xxxx
    masterslave:
      # 读写分离配置
      load-balance-algorithm-type: round_robin
      # 最终的数据源名称
      name: dataSource
      # 主库数据源名称
      master-data-source-name: master
      # 从库数据源名称列表,多个逗号分隔
      slave-data-source-names: slave
    props:
      # 开启SQL显示,默认false
      sql:
        show: true
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml

三、目录结构

 四、测试

 可以看到查询走的是slave库,更新走的是master库。

五、顺便提一杯奥,关于mybatis.mapper-locations配置问题,分为以下几种情况

1、数据库xml文件在resource文件下,与java所在包名不同,如下图:

这种情况,application.yml文件必须配置mapper-locations,否则程序运行的时候会报找不到xml文件。

2、数据库xml文件在resource文件下,与java所在包名相同,如下图:

 这种情况,无需配置mapper-locations,程序也能够正常运行。

3、数据库xml文件在java包下面时,这种情况不可使用mapper-locations,可在pom.xml的<build>标签中添加如下:

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值