Spring Boot 整合ShardingSphere 实现读写分离, 分库分表
1. 导入依赖
<dependency><groupId>org.apache.shardingsphere</groupId><artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId><version>5.1.1</version></dependency>
2. 编写 application.yml
网上视频教程
# mybatis-plus 配置mybatis-plus:mapper-locations: classpath*: mapper/*.xmlconfiguration:log-impl: org.apache.ibatis.logging.stdout.stdOutImpl # 打印 SQL 语句# Shardingsphere 配置, 通用配置, 必须有spring:shardingsphere:datasource:common:type: com.zaxxer.hikari.HikariDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: root# 一主, 一从names: master, slave0master:type: com.zaxxer.hikari.HikariDataSourcedriverClassName: com.mysql.cj.jdbc.DriverjdbcUrl: jdbc:mysql://localhost:3306/demo_ds_0?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8username: rootpassword:slave0:type: com.zaxxer.hikari.HikariDataSourcedriverClassName: com.mysql.cj.jdbc.DriverjdbcUrl: jdbc:mysql://localhost:3306/demo_ds_1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8username: rootpassword:rules:replica-query:data-sources:ms: # ms 名字自定义的primary-data-source-name: master # 主数据源名称 , 这个必须和前面配置的 [names] 名字一致replica-data-source-names: slave0 # 从数据源名称 多个从库 , 分割load-balancer-name: round-robin # 负载均很算法load-balancers:round-robin:props:wordId: 1 # 负载均衡算法属性配置, 没撒意义, 但是不加不能够使用props:sql-show: true # 打印SQL
官网教程
spring:shardingsphere:datasource:names: ds_0, ds_1ds_0:type: com.zaxxer.hikari.HikariDataSourcedriverClassName: com.mysql.cj.jdbc.DriverjdbcUrl: jdbc:mysql://localhost:3306/demo_ds_0?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8username: rootpassword:ds_1:type: com.zaxxer.hikari.HikariDataSourcedriverClassName: com.mysql.cj.jdbc.DriverjdbcUrl: jdbc:mysql://localhost:3306/demo_ds_1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8username: rootpassword:rules:sharding:tables:
https://www.bilibili.com/video/BV1L5411g7KP/?spm_id_from=333.788.video.desc.click
分表

