1. 程式人生 > 其它 >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