版本及環(huán)境
- springboot:2.3.1.RELEASE
- shardingsphere:4.0.0-RC1
- 配置好主從復(fù)制的2-3臺(tái)mysql節(jié)點(diǎn)
maven依賴
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<!--mysql讀寫(xiě)分離 sharding-jdbc4.x版本-->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>${shardingsphere-version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-core-common</artifactId>
<version>${shardingsphere-version}</version>
</dependency>
配置文件
db:
db: ds
db0: ds0
db1: ds1
spring:
main:
allow-bean-definition-overriding: true
shardingsphere:
datasource:
names: ${db.db},${db.db0},${db.db1}
# 配置主庫(kù)
ds:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.77.20:3316/test?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 123456
#最大連接數(shù)
maxPoolSize: 10
minPoolSize: 5
ds0: # 配置第一個(gè)從庫(kù)
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.77.20:3317/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 123456
maxPoolSize: 5
minPoolSize: 2
ds1: # 配置第二個(gè)從庫(kù)
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.77.20:3317/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 123456
maxPoolSize: 5
minPoolSize: 2
# 配置默認(rèn)數(shù)據(jù)源愉昆,主要用于寫(xiě)倔丈,注意一定要配讀寫(xiě)分離黔夭,否則會(huì)把所有節(jié)點(diǎn)都當(dāng)作slave蒋譬,導(dǎo)致master壓力太大
sharding:
default-data-source-name: ${db.db}
# 配置讀寫(xiě)分離马昙,配置之前一定要確認(rèn)數(shù)據(jù)庫(kù)做了主從復(fù)制
masterslave:
# 名稱岖寞,任意
name: ms
load-balance-algorithm-type: round_robin # 配置從庫(kù)選擇策略箱熬,提供輪詢與隨機(jī)钧萍,這里選擇用輪詢//random 隨機(jī) //round_robin 輪詢
master-data-source-name: ${db.db}
slave-data-source-names: ${db.db0},${db.db1}
props:
sql: # 開(kāi)啟SQL顯示春畔,默認(rèn)值: false脱货,注意:僅配置讀寫(xiě)分離時(shí)不會(huì)打印日志!B梢獭振峻!
show: true