一.先知道 sharding-jdbc 是個什么 可以再官網看一下: https://shardingsphere.apache.org/index_zh.html
二.引入maven 依賴, 注意每個版本的配置不一樣,我這里是4.X 其他版本的配置可以去官網查看
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.3</version>
</dependency>
三. 如果出現 sqlTemplate 等異常 說明項目里面引入了 druid-spring-boot-starter 依賴 和 原生的 druid 沖突了 這里需要使用原生的或者可以把 依賴換成這個
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
四. yml 配置 分表配置,這里只是簡單的分表
spring:
shardingsphere:
datasource:
names: ds01
ds01: # 數據源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.254.106:5166/evaluate_center?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: admin
password: admindgg
sharding:
tables: # 分表配置
test:
actualDataNodes: ds01.test${0..1}
# 分片鍵(分表字段)這里通過id 分表,具體字段可以自己定義,分表規則
table-strategy:
inline:
shardingColumn: id
algorithm-expression: test${id % 2}
keyGenerator:
type: SNOWFLAKE
column: id
props:
sql:
# 打印SQL
show: true
五. 創建數據庫表 test0, test1
六. 然后創建對應的實體,注意這里的@TableName表名不要給后綴比如test0,test1,直接寫test,不然只會插入指定的表
七. 創建對應的controller,service,mapper,這里就不贅述這個了
八. 調用測試,調用添加接口可以看到數據插入執行的sql,並且查看數據庫都有數據,可以看出id 為偶數的在test0,id 為奇數的在test1
test0
test1
九. 測試查詢: 通過分表id 查詢,和某個字段分頁查詢
通過id 查詢
分頁查詢,如果使用mybatis-plus 分頁記得加上分頁插件