ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-05-16 19:31:57  阅读:194  来源: 互联网

标签:xml mapper JDBC springboot 数据源 jdbc master Sharding true


一、引入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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有