其他分享
首页 > 其他分享> > springboot + mybatis + Sharding-JDBC实现读写分离

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>
————————————————
版权声明:本文为CSDN博主「东京的雪铺满巴黎的道」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xiaoxiaoxiao_Ming/article/details/121267052

标签:xml,mapper,JDBC,springboot,数据源,jdbc,master,Sharding,true
来源: https://www.cnblogs.com/javalinux/p/16278214.html