1. 为什么需要分库分表(简单分析)?
- 单表性能容易达到极限
- 单库QPS查询过高 2. 常用的分库分表工具
- MyCat
- Sharding
- 根据自身业务选择适合自己的工具 3. Sharding整合SpringBoot使用
- 引入Maven依赖(注意版本,不同Sharding版本yml配置属性会不同很容易踩坑)
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.1.0</version>
</dependency>
- 使用yml文件进行配置
spring: application: name: sharding-jdbc-demo shardingsphere: mode: type: Memory #内存模式,无需持久化 rules: sharding: tables: #自定义逻辑表名 user: #实际库名.表名(会根据分片规则进行填充$) actualDataNodes: user-$->{0..1}.user_$->{0..1} databaseStrategy: standard: shardingColumn: user_id shardingAlgorithmName: database-inline tableStrategy: standard: shardingColumn: user_id shardingAlgorithmName: table-inline shardingAlgorithms: #分库规则(使用的是标准分片算法,根据列进行运算分片) database-inline: type: INLINE props: algorithm-expression: user-$->{user_id%2} ##分表规则(使用的是标准分片算法,根据列进行运算分片) table-inline: type: INLINE props: algorithm-expression: user_$->{user_id%2} #配置数据源(注意type这是5.1版本的属性名,5.1之前不是用这个的,使用的是dataSourceClassName)官方文档也是使用这个 datasource: names: user-0,user-1 user-0: type: com.zaxxer.hikari.HikariDataSource driverClassName: com.mysql.cj.jdbc.Driver jdbcUrl: jdbc:mysql://localhost:3308/user_0?useUnicode=true username: root password: 123456 user-1: type: com.zaxxer.hikari.HikariDataSource driverClassName: com.mysql.cj.jdbc.Driver jdbcUrl: jdbc:mysql://localhost:3308/user_1?useUnicode=true username: root password: 123456 props: sql-show: true # 开启sql日志打印 - 其余就是引入mybatis-plus的常规操作
- 在实体类用加入TableName的注解需要与自定义逻辑表名一致,不然无法分库分表
- 控制台日志
- 1.通过分片规则匹配的实际库名
- 2.通过分片规则匹配的实际表名 4. 总结
- 一定要注意不同版本间的sharding属性变化的问题
- 简单了搭建demo,通过日志debug能大致认识分库分表的逻辑
- 源码地址(有读写分离的相关配置demo):github.com/partick33/s…
- 请各位大佬发现错误,能指导菜鸟小弟
- 菜鸟也想努力进大厂,加油