1.基本介绍

1.1 Sharding Sphere

是一款分布式数据库解决方案 ,详情 官网传送门

1.2 什么是分库分表

数据库数据量不可控的,随着时间和业务发展,造成表里面数据越来越多,如果再去对数据库表curd操作时候,造成性能问题。所以考虑到了对数据库进行拆分。有两个方案

  1. 硬件层面上 (存在瓶颈,且消耗资源)
  2. 软件层面上

    1.2.1 分库分表的方式

  3. 垂直切分:垂直分库和垂直分表

  4. 水平切分:水平分库和水平分表

    垂直分库: 根据业务场景进行分库

    image.png

    垂直分表:一个表的字段过多或者把该表的常用字段放在一个表中,不常用的字段,大字段放在另一个表中,减少磁盘IO,提高哦访问效率

    image.png

    水平分库:同一个表的数据按一定规则拆分到不同的数据库中,每个库可以放在不同的服务器上。解决了单库大数据,高并发的性能瓶颈,提高稳定性和高可用性。

    image.png

水平分表:同一个数据库内,把同一张表的数据按照一定规则拆到多个表,解决性能问题和避免IO锁表的几率。

image.png

1.2.2 分库分表带来的问题

事务一致性问题

数据分布在不同的数据表或数据库中,会带来分布式事务问题。

跨节点关联查询

如果有跨数据库或者跨节点分库,不在一个库或不在一个服务器内 不能进行关联查询,只能两次查询然后拼接。

跨节点分页、排序函数

跨节点order By limit会比较复杂 , Max、Min、Sum、Count 等函数也会出现相应的问题,都要多次查询然后汇总。

主键避重

在分库分表环境下数据库自增主键将不能使用,为了避免主键重复需要使用分布式ID

公共表

对于一些变动小,频率低的字典,公共表,将这些表在每个数据库都存一份,避免jion查询复杂。所以维护需要同时维护。

2 Sharding JDBC

定位为轻量级Java框架,在Java的JDBC层提供的额外服务。
sharding Sphere - 图5

2.1 环境搭建

springboot 2.4.2 + mybatisPlus + Lombok + sharding jdbc4.1.1

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.4.2</version>
  9. <relativePath/>
  10. </parent>
  11. <groupId>com.rem</groupId>
  12. <artifactId>shardingjdbc</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>shardingjdbc</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-web</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-test</artifactId>
  27. </dependency>
  28. <!--注解处理器 自动解析yml文件到config配置类中-->
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-configuration-processor</artifactId>
  32. <optional>true</optional>
  33. </dependency>
  34. <!--连接数据库-->
  35. <dependency>
  36. <groupId>com.baomidou</groupId>
  37. <artifactId>mybatis-plus-boot-starter</artifactId>
  38. <version>3.4.2</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>mysql</groupId>
  42. <artifactId>mysql-connector-java</artifactId>
  43. </dependency>
  44. <dependency>
  45. <groupId>com.alibaba</groupId>
  46. <artifactId>druid</artifactId>
  47. <version>1.2.6</version>
  48. </dependency>
  49. <!--脚手架-->
  50. <dependency>
  51. <groupId>org.projectlombok</groupId>
  52. <artifactId>lombok</artifactId>
  53. <optional>true</optional>
  54. </dependency>
  55. <dependency>
  56. <groupId>org.apache.commons</groupId>
  57. <artifactId>commons-lang3</artifactId>
  58. <version>3.8.1</version>
  59. </dependency>
  60. <dependency>
  61. <groupId>cn.hutool</groupId>
  62. <artifactId>hutool-all</artifactId>
  63. <version>5.4.0</version>
  64. </dependency>
  65. <!--sharding-jdbc-->
  66. <dependency>
  67. <groupId>org.apache.shardingsphere</groupId>
  68. <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
  69. <version>4.1.1</version>
  70. </dependency>
  71. </dependencies>
  72. <build>
  73. <plugins>
  74. <plugin>
  75. <groupId>org.springframework.boot</groupId>
  76. <artifactId>spring-boot-maven-plugin</artifactId>
  77. <configuration>
  78. <excludes>
  79. <exclude>
  80. <groupId>org.projectlombok</groupId>
  81. <artifactId>lombok</artifactId>
  82. </exclude>
  83. </excludes>
  84. </configuration>
  85. </plugin>
  86. </plugins>
  87. </build>
  88. </project>

2.2 单库双表水平分片

数据库准备

  1. -- auto-generated definition
  2. create table t_order_1
  3. (
  4. id bigint auto_increment
  5. primary key,
  6. orderCode varchar(100) null,
  7. buyId bigint null,
  8. amount decimal(11, 2) null,
  9. productId bigint null,
  10. productName varchar(100) null
  11. )
  12. comment '订单表';
  13. -- auto-generated definition
  14. create table t_order_2
  15. (
  16. id bigint auto_increment
  17. primary key,
  18. orderCode varchar(100) null,
  19. buyId bigint null,
  20. amount decimal(11, 2) null,
  21. productId bigint null,
  22. productName varchar(100) null
  23. )
  24. comment '订单表';
  1. #shardingjdbc分片策略 单库双表水平分片
  2. spring:
  3. shardingsphere:
  4. datasource:
  5. #配置数据源,给数据源起名称
  6. names: m1
  7. m1:
  8. #配置数据源具体内容,包含连接池,驱动,地址,用户名和密码
  9. type: com.alibaba.druid.pool.DruidDataSource
  10. url: jdbc:mysql://192.168.19.128:3306/so?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  11. driverClassName: com.mysql.cj.jdbc.Driver
  12. username: root
  13. password: 123456
  14. sharding:
  15. tables:
  16. #指定order表分布情况,配置表在哪个数据库里面,表名称都是什么 m1.t_order_1 , m1.t_order_2
  17. t_order:
  18. actualDataNodes: m1.t_order_$->{1..2}
  19. # 指定t_order表里面主键id 生成策略 SNOWFLAKE
  20. keyGenerator:
  21. column: id
  22. type: SNOWFLAKE
  23. # 限定表=====指定分片策略 约定id值偶数添加到t_order_1表,如果id是奇数添加到t_order_2表
  24. tableStrategy:
  25. inline:
  26. shardingColumn: id
  27. algorithmExpression: t_order_${id % 2 +1}
  28. # 全局=====指定分片策略 约定id值偶数添加到t_order_1表,如果id是奇数添加到t_order_2表
  29. # defaultTableStrategy:
  30. # inline:
  31. # shardingColumn: id
  32. # algorithmExpression: t_order_$->{id % 2 +1}
  33. # 打开sql输出日志
  34. props:
  35. sql:
  36. show: true
  37. # 一个实体类对应两张表,覆盖
  38. main:
  39. allowBeanDefinitionOverriding: true
  40. mybatisPlus:
  41. configuration:
  42. # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  43. mapUnderscoreToCamelCase: false
  44. callSettersOnNulls: true

演示结果 偶数插入1表,奇数插入到2表
image.png

数据库结果
image.png

查询
image.png

2.3 双库双表水平分片

数据库准备

  1. -- auto-generated definition
  2. create table t_course_1
  3. (
  4. cid bigint auto_increment
  5. primary key,
  6. cname varchar(100) null,
  7. userId bigint null,
  8. cstatus varchar(100) null
  9. );
  10. -- auto-generated definition
  11. create table t_course_2
  12. (
  13. cid bigint auto_increment
  14. primary key,
  15. cname varchar(100) null,
  16. userId bigint null,
  17. cstatus varchar(100) null
  18. );
  1. #shardingjdbc分片策略 双库双表水平分片 实际上一张表根据两个字段被分成4个表,在实际中很少用
  2. spring:
  3. shardingsphere:
  4. datasource:
  5. #配置数据源,给数据源起名称
  6. names: m1,m2
  7. m1:
  8. #配置数据源具体内容,包含连接池,驱动,地址,用户名和密码
  9. type: com.alibaba.druid.pool.DruidDataSource
  10. url: jdbc:mysql://192.168.19.128:3306/edu_db_1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  11. driverClassName: com.mysql.cj.jdbc.Driver
  12. username: root
  13. password: 123456
  14. m2:
  15. #配置数据源具体内容,包含连接池,驱动,地址,用户名和密码
  16. type: com.alibaba.druid.pool.DruidDataSource
  17. url: jdbc:mysql://192.168.19.128:3306/edu_db_2?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  18. driverClassName: com.mysql.cj.jdbc.Driver
  19. username: root
  20. password: 123456
  21. sharding:
  22. tables:
  23. #指定course表分布情况,配置表在哪个数据库里面,表名称都是什么 m1.t_course_1 , m1.t_course_2
  24. t_course:
  25. actualDataNodes: m$->{1..2}.t_course_$->{1..2}
  26. # 指定t_course表里面主键id 生成策略 SNOWFLAKE
  27. keyGenerator:
  28. column: cid
  29. type: SNOWFLAKE
  30. # 限定表=====指定分片策略 约定id值偶数添加到t_course_1表,如果id是奇数添加到t_course_2表
  31. tableStrategy:
  32. inline:
  33. shardingColumn: cid
  34. algorithmExpression: t_course_${cid % 2 +1}
  35. # 限定库=====指定分片策略 约定userId是偶数添加m1,是奇数添加m2
  36. databaseStrategy:
  37. inline:
  38. shardingColumn: userId
  39. algorithmExpression: m$->{userId % 2 + 1}
  40. # 全局库
  41. # default:
  42. # databaseStrategy:
  43. # inline: user_id
  44. # shardingColumn: m$->{userId % 2 + 1}
  45. # 打开sql输出日志
  46. props:
  47. sql:
  48. show: true
  49. # 一个实体类对应两张表,覆盖
  50. main:
  51. allowBeanDefinitionOverriding: true
  52. mybatis-plus:
  53. configuration:
  54. map-underscore-to-camel-case: false
  55. call-setters-on-nulls: true

插入数据 根据数据插入不同的库和表
image.png
数据库结果
image.png
查询结果:
image.png

2.4 垂直分库

数据库准备

  1. -- auto-generated definition
  2. create table t_user
  3. (
  4. userId bigint auto_increment
  5. primary key,
  6. username varchar(100) null,
  7. ustatus varchar(100) null
  8. );

yml配置

  1. #shardingjdbc分片策略 垂直分库 专库专表使用
  2. spring:
  3. shardingsphere:
  4. datasource:
  5. #配置数据源,给数据源起名称
  6. names: m1,m2,v0
  7. m1:
  8. #配置数据源具体内容,包含连接池,驱动,地址,用户名和密码
  9. type: com.alibaba.druid.pool.DruidDataSource
  10. url: jdbc:mysql://192.168.19.128:3306/edu_db_1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  11. driverClassName: com.mysql.cj.jdbc.Driver
  12. username: root
  13. password: 123456
  14. m2:
  15. #配置数据源具体内容,包含连接池,驱动,地址,用户名和密码
  16. type: com.alibaba.druid.pool.DruidDataSource
  17. url: jdbc:mysql://192.168.19.128:3306/edu_db_2?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  18. driverClassName: com.mysql.cj.jdbc.Driver
  19. username: root
  20. password: 123456
  21. v0:
  22. #配置数据源具体内容,包含连接池,驱动,地址,用户名和密码
  23. type: com.alibaba.druid.pool.DruidDataSource
  24. url: jdbc:mysql://192.168.19.128:3306/user_db?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  25. driverClassName: com.mysql.cj.jdbc.Driver
  26. username: root
  27. password: 123456
  28. sharding:
  29. tables:
  30. #指定course表分布情况,配置表在哪个数据库里面,表名称都是什么 m1.t_course_1 , m1.t_course_2
  31. t_course:
  32. actualDataNodes: m$->{1..2}.t_course_$->{1..2}
  33. # 指定t_course表里面主键id 生成策略 SNOWFLAKE
  34. keyGenerator:
  35. column: cid
  36. type: SNOWFLAKE
  37. # 限定表=====指定分片策略 约定id值奇数添加到t_course_1表,如果id是偶数添加到t_course_2表
  38. tableStrategy:
  39. inline:
  40. shardingColumn: cid
  41. algorithmExpression: t_course_${cid % 2 +1}
  42. # 限定库=====指定分片策略 约定userId是偶数添加m1,是奇数添加m2
  43. databaseStrategy:
  44. inline:
  45. shardingColumn: userId
  46. algorithmExpression: m$->{userId % 2 + 1}
  47. # 垂直分库 专表专用
  48. t_user:
  49. actualDataNodes: v$->{0}.t_user
  50. keyGenerator:
  51. type: SNOWFLAKE
  52. column: userId
  53. # 打开sql输出日志
  54. props:
  55. sql:
  56. show: true
  57. # 一个实体类对应两张表,覆盖
  58. main:
  59. allowBeanDefinitionOverriding: true
  60. mybatis-plus:
  61. configuration:
  62. map-underscore-to-camel-case: false
  63. call-setters-on-nulls: true

演示结果:
image.png
查询:

image.png

2.5 广播表配置

在每个数据库都创建这张表

  1. -- auto-generated definition
  2. create table t_dict
  3. (
  4. dictId bigint auto_increment
  5. primary key,
  6. status varchar(100) null,
  7. value varchar(100) null
  8. );
  1. #shardingjdbc分片策略 广播配置,配置公共表
  2. spring:
  3. shardingsphere:
  4. datasource:
  5. #配置数据源,给数据源起名称
  6. names: m1,m2,v0
  7. m1:
  8. #配置数据源具体内容,包含连接池,驱动,地址,用户名和密码
  9. type: com.alibaba.druid.pool.DruidDataSource
  10. url: jdbc:mysql://192.168.19.128:3306/edu_db_1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  11. driverClassName: com.mysql.cj.jdbc.Driver
  12. username: root
  13. password: 123456
  14. m2:
  15. #配置数据源具体内容,包含连接池,驱动,地址,用户名和密码
  16. type: com.alibaba.druid.pool.DruidDataSource
  17. url: jdbc:mysql://192.168.19.128:3306/edu_db_2?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  18. driverClassName: com.mysql.cj.jdbc.Driver
  19. username: root
  20. password: 123456
  21. v0:
  22. #配置数据源具体内容,包含连接池,驱动,地址,用户名和密码
  23. type: com.alibaba.druid.pool.DruidDataSource
  24. url: jdbc:mysql://192.168.19.128:3306/user_db?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  25. driverClassName: com.mysql.cj.jdbc.Driver
  26. username: root
  27. password: 123456
  28. sharding:
  29. # 广播配置 全局公共配置表
  30. broadcastTables: t_dict
  31. tables:
  32. # 广播表
  33. t_dict:
  34. keyGenerator:
  35. column: dictId
  36. type: SNOWFLAKE
  37. #指定course表分布情况,配置表在哪个数据库里面,表名称都是什么 m1.t_course_1 , m1.t_course_2
  38. t_course:
  39. actualDataNodes: m$->{1..2}.t_course_$->{1..2}
  40. # 指定t_course表里面主键id 生成策略 SNOWFLAKE
  41. keyGenerator:
  42. column: cid
  43. type: SNOWFLAKE
  44. # 限定表=====指定分片策略 约定id值奇数添加到t_course_1表,如果id是偶数添加到t_course_2表
  45. tableStrategy:
  46. inline:
  47. shardingColumn: cid
  48. algorithmExpression: t_course_${cid % 2 +1}
  49. # 限定库=====指定分片策略 约定userId是偶数添加m1,是奇数添加m2
  50. databaseStrategy:
  51. inline:
  52. shardingColumn: userId
  53. algorithmExpression: m$->{userId % 2 + 1}
  54. # 垂直分库
  55. t_user:
  56. actualDataNodes: v0.t_user
  57. keyGenerator:
  58. column: userId
  59. type: SNOWFLAKE
  60. # 无需分库分表的数据源配置
  61. default-data-source-name: v0
  62. # 打开sql输出日志
  63. props:
  64. sql:
  65. show: true
  66. # 一个实体类对应两张表,覆盖
  67. main:
  68. allowBeanDefinitionOverriding: true
  69. mybatis-plus:
  70. configuration:
  71. map-underscore-to-camel-case: false
  72. call-setters-on-nulls: true

插入一条数据,每个库里的表都会创建一条数据
image.png

数据库显示
image.png

查询数据
image.png

2.6 水平分库 + 读写分离

准备主从数据库配置 docker配置简单 传送门
配置一主两从服务器

  1. ######################################水平分库分表+读写分离配置############################################################
  2. ######################################一主多从配置############################################################
  3. spring:
  4. shardingsphere:
  5. datasource:
  6. #配置数据源 两主两从
  7. names: m1,s1,s2
  8. m1:
  9. type: com.alibaba.druid.pool.DruidDataSource
  10. url: jdbc:mysql://192.168.19.128:3306/so?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  11. driverClassName: com.mysql.cj.jdbc.Driver
  12. username: root
  13. password: 123456
  14. s1:
  15. type: com.alibaba.druid.pool.DruidDataSource
  16. url: jdbc:mysql://192.168.19.128:3307/so?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  17. driverClassName: com.mysql.cj.jdbc.Driver
  18. username: root
  19. password: 123456
  20. s2:
  21. type: com.alibaba.druid.pool.DruidDataSource
  22. url: jdbc:mysql://192.168.19.128:3308/so?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  23. driverClassName: com.mysql.cj.jdbc.Driver
  24. username: root
  25. password: 123456
  26. sharding:
  27. tables:
  28. #表配置 结合数据源
  29. t_order:
  30. actualDataNodes: ds0.t_order_$->{1..2}
  31. # 分表策略
  32. tableStrategy:
  33. inline:
  34. shardingColumn: id
  35. algorithmExpression: t_order_${id % 2 +1}
  36. keyGenerator:
  37. column: id
  38. type: SNOWFLAKE
  39. # 主从配置
  40. masterSlaveRules:
  41. ds0:
  42. masterDataSourceName: m1
  43. slaveDataSourceNames: s1,s2
  44. bindingTables: t_course
  45. props:
  46. sql:
  47. show: true
  48. # 一个实体类对应两张表,覆盖
  49. main:
  50. allowBeanDefinitionOverriding: true
  51. mybatisPlus:
  52. configuration:
  53. # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  54. mapUnderscoreToCamelCase: false
  55. callSettersOnNulls: true
  56. ######################################多主多从配置############################################################
  57. #spring:
  58. # shardingsphere:
  59. # datasource:
  60. # #配置数据源 两主两从
  61. # names: m1,m2,s1,s2
  62. # m1:
  63. # type: com.alibaba.druid.pool.DruidDataSource
  64. # url: jdbc:mysql://192.168.19.128:3306/edu_db_1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  65. # driverClassName: com.mysql.cj.jdbc.Driver
  66. # username: root
  67. # password: 123456
  68. # m2:
  69. # type: com.alibaba.druid.pool.DruidDataSource
  70. # url: jdbc:mysql://192.168.19.128:3306/edu_db_2?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  71. # driverClassName: com.mysql.cj.jdbc.Driver
  72. # username: root
  73. # password: 123456
  74. # s1:
  75. # type: com.alibaba.druid.pool.DruidDataSource
  76. # url: jdbc:mysql://192.168.19.128:3307/edu_db_1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  77. # driverClassName: com.mysql.cj.jdbc.Driver
  78. # username: root
  79. # password: 123456
  80. # s2:
  81. # type: com.alibaba.druid.pool.DruidDataSource
  82. # url: jdbc:mysql://192.168.19.128:3307/edu_db_2?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  83. # driverClassName: com.mysql.cj.jdbc.Driver
  84. # username: root
  85. # password: 123456
  86. # sharding:
  87. # tables:
  88. # #表配置 结合数据源
  89. # t_course:
  90. # actualDataNodes: ds$->{0..1}.t_course_$->{1..2}
  91. # # 分表策略
  92. # tableStrategy:
  93. # inline:
  94. # shardingColumn: cid
  95. # algorithmExpression: t_course_${cid % 2 +1}
  96. # keyGenerator:
  97. # column: cid
  98. # type: SNOWFLAKE
  99. # # 分库策略
  100. # databaseStrategy:
  101. # inline:
  102. # shardingColumn: userId
  103. # algorithmExpression: ds$->{userId % 2}
  104. # # 主从配置
  105. # masterSlaveRules:
  106. # ds0:
  107. # masterDataSourceName: m1
  108. # slaveDataSourceNames: s1,s2
  109. # ds1:
  110. # masterDataSourceName: m2
  111. # slaveDataSourceNames: s1,s2
  112. # # bindingTables: t_course
  113. # props:
  114. # sql:
  115. # show: true
  116. # # 一个实体类对应两张表,覆盖
  117. # main:
  118. # allowBeanDefinitionOverriding: true
  119. #
  120. #
  121. #mybatisPlus:
  122. # configuration:
  123. # # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  124. # mapUnderscoreToCamelCase: false
  125. # callSettersOnNulls: true

插入数据 master 逻辑插入
image.png

查询数据 默认slave会轮询去查询数据
image.png

3 sharding proxy

3.1 什么是 sharding proxy

透明化的数据库代理端,用于对异构语言的支持。
sharding Sphere - 图19
下载地址 https://archive.apache.org/dist/shardingsphere/
下载完成后解压 windows环境会存在jar包过长导致解压时文件名会截断 ,解决办法:

  1. tar zxvf apache-shardingsphere-${RELEASE.VERSION}-sharding-proxy-bin.tar.gz

3.2 sharding proxy配置

server.yaml配置
不使用服务治理的情况下, 不开启zookeeper

  1. # 服务治理,开启zookeeper 也可以使用nacos等
  2. orchestration:
  3. orchestration_ds:
  4. orchestrationType: registry_center,config_center,distributed_lock_manager
  5. instanceType: zookeeper
  6. serverLists: localhost:2181
  7. namespace: orchestration
  8. props:
  9. overwrite: false
  10. retryIntervalMilliseconds: 500
  11. timeToLiveSeconds: 60
  12. maxRetries: 3
  13. operationTimeoutMilliseconds: 500
  14. # 权限验证
  15. authentication:
  16. users:
  17. root: # 自定义用户名
  18. password: 123456 # 自定义密码
  19. sharding:
  20. password: 123456
  21. authorizedSchemas: sharding_db # 该用户授权可访问的数据库,多个用逗号分隔。缺省将拥有root权限,可访问全部数据库。
  22. #全局配置
  23. props:
  24. max.connections.size.per.query: 1
  25. acceptor.size: 16 #用于设置接收客户端请求的工作线程个数,默认为CPU核数*2
  26. executor.size: 16 # Infinite by default.
  27. proxy.frontend.flush.threshold: 128 # The default value is 128.
  28. # LOCAL: Proxy will run with LOCAL transaction.
  29. # XA: Proxy will run with XA transaction.
  30. # BASE: Proxy will run with B.A.S.E transaction.
  31. proxy.transaction.type: LOCAL
  32. proxy.opentracing.enabled: false #是否开启链路追踪功能,默认为不开启。详情请参见[链路追踪](/cn/features/orchestration/apm/)
  33. proxy.hint.enabled: false
  34. query.with.cipher.column: true #是否使用密文列查询
  35. sql.show: true # 是否显示sql语句
  36. allow.range.query.with.inline.sharding: false

config-sharding.yaml 配置数据分片

  1. schemaName: sharding_db
  2. dataSources:
  3. m1:
  4. url: jdbc:mysql://192.168.19.128:3306/so?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  5. username: root
  6. password: 123456
  7. connectionTimeoutMilliseconds: 30000
  8. idleTimeoutMilliseconds: 60000
  9. maxLifetimeMilliseconds: 1800000
  10. maxPoolSize: 50
  11. shardingRule:
  12. tables:
  13. t_order:
  14. actualDataNodes: m1.t_order_$->{1..2}
  15. keyGenerator:
  16. column: id
  17. type: SNOWFLAKE
  18. tableStrategy:
  19. inline:
  20. shardingColumn: id
  21. algorithmExpression: t_order_${id % 2 +1}

config-master_slave.yaml 配置读写分离 或读写分离+数据分片

  1. # 读写分离
  2. schemaName: master_slave_db
  3. dataSources:
  4. m1:
  5. url: jdbc:mysql://192.168.19.128:3306/so?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  6. username: root
  7. password: 123456
  8. connectionTimeoutMilliseconds: 30000
  9. idleTimeoutMilliseconds: 60000
  10. maxLifetimeMilliseconds: 1800000
  11. maxPoolSize: 50
  12. s1:
  13. url: jdbc:mysql://192.168.19.128:3306/so?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  14. username: root
  15. password: 123456
  16. connectionTimeoutMilliseconds: 30000
  17. idleTimeoutMilliseconds: 60000
  18. maxLifetimeMilliseconds: 1800000
  19. maxPoolSize: 50
  20. s2:
  21. url: jdbc:mysql://192.168.19.128:3308/so?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  22. username: root
  23. password: 123456
  24. connectionTimeoutMilliseconds: 30000
  25. idleTimeoutMilliseconds: 60000
  26. maxLifetimeMilliseconds: 1800000
  27. maxPoolSize: 50
  28. masterSlaveRule:
  29. name: ms_ds
  30. masterDataSourceName: m1
  31. slaveDataSourceNames:
  32. - s1
  33. - s2
  34. ######################################################################################################
  35. #
  36. # If you want to connect to MySQL, you should manually copy MySQL driver to lib directory.
  37. #
  38. ######################################################################################################
  39. # 读写分离 + 一主多从
  40. # schemaName: sharding_master_slave_db
  41. # dataSources:
  42. # ds0:
  43. # url: jdbc:mysql://192.168.19.128:3306/so?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  44. # username: root
  45. # password: 123456
  46. # connectionTimeoutMilliseconds: 30000
  47. # idleTimeoutMilliseconds: 60000
  48. # maxLifetimeMilliseconds: 1800000
  49. # maxPoolSize: 65
  50. # ds0_slave0:
  51. # url: jdbc:mysql://192.168.19.128:3307/so?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  52. # username: root
  53. # password: 123456
  54. # connectionTimeoutMilliseconds: 30000
  55. # idleTimeoutMilliseconds: 60000
  56. # maxLifetimeMilliseconds: 1800000
  57. # maxPoolSize: 65
  58. # ds0_slave1:
  59. # url: jdbc:mysql://192.168.19.128:3308/so?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
  60. # username: root
  61. # password: 123456
  62. # connectionTimeoutMilliseconds: 30000
  63. # idleTimeoutMilliseconds: 60000
  64. # maxLifetimeMilliseconds: 1800000
  65. # maxPoolSize: 65
  66. # shardingRule:
  67. # tables:
  68. # t_order:
  69. # actualDataNodes: ms_ds${0}.t_order_${1..2}
  70. # databaseStrategy:
  71. # inline:
  72. # shardingColumn: buyId
  73. # algorithmExpression: ms_ds${0}
  74. # tableStrategy:
  75. # inline:
  76. # shardingColumn: id
  77. # algorithmExpression: t_order_${id % 2 +1}
  78. # keyGenerator:
  79. # type: SNOWFLAKE
  80. # column: id
  81. # bindingTables:
  82. # - t_order
  83. # broadcastTables:
  84. # - t_config
  85. # defaultDataSourceName: ds0
  86. # defaultTableStrategy:
  87. # none:
  88. # masterSlaveRules:
  89. # ms_ds0:
  90. # masterDataSourceName: ds0
  91. # slaveDataSourceNames:
  92. # - ds0_slave0
  93. # - ds0_slave1
  94. # loadBalanceAlgorithmType: ROUND_ROBIN

3.3 使用docker 配置sharding proxy

使用稳定版本4.1.1 ,配置一个zookeeper,两个proxy,三个mysql(一主两从),一个nginx
docker简单使用

  1. docker pull apache/sharding-proxy:4.1.1

proxy启动端口3308 ,映射外部端口3540, 配置mysqly需要外部挂载配置目录和驱动 在本地centos做好准备/home/sharding/conf,创建,/home/sharding/ext-lib

  1. docker run --name shardingproxy -d -v /home/sharding/conf:/opt/sharding-proxy/conf -v /home/sharding/ext-lib:/opt/sharding-proxy/ext-lib --env PORT=3308 -p3540:3308 apache/sharding-proxy:4.1.1

nginx配置

  1. worker_processes 1;
  2. events {
  3. worker_connections 1024;
  4. }
  5. stream {
  6. # sharding proxy
  7. upstream sharding {
  8. server 192.168.19.128:3540;
  9. server 192.168.19.128:3541;
  10. }
  11. server {
  12. listen 13306;
  13. proxy_pass sharding;
  14. }
  15. }
  16. http {
  17. include mime.types;
  18. default_type application/octet-stream;
  19. sendfile on;
  20. keepalive_timeout 65;
  21. server {
  22. listen 80;
  23. server_name localhost;
  24. location / {
  25. root html;
  26. index index.html index.htm;
  27. }
  28. error_page 500 502 503 504 /50x.html;
  29. location = /50x.html {
  30. root html;
  31. }
  32. }
  33. }

image.png
创建一个sprigboot 项目 配置

  1. spring:
  2. datasource:
  3. driver-class-name: com.mysql.cj.jdbc.Driver
  4. url: jdbc:mysql://192.168.19.128:13306/master_slave_db?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8&allowPublicKeyRetrieval=true
  5. #url: jdbc:mysql://192.168.19.128:3540/master_slave_db?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8&allowPublicKeyRetrieval=true
  6. username: root
  7. password: 123456
  8. type: com.alibaba.druid.pool.DruidDataSource
  9. mybatis-plus:
  10. configuration:
  11. map-underscore-to-camel-case: false
  12. call-setters-on-nulls: true
  13. #配置自定义的mapper文件 (多表查询适用)
  14. mapper-locations: classpath*:mapper/*.xml
  15. #配置实体对象扫描包===在mapper.xml中简化使用
  16. type-aliases-package: com.rem.shardingproxy.pojo

查询
image.png

4 sharding -ui 选用

官网下载
linux 解压后 直接在bin目录下运行
也可以在conf下修改配置
可以查看节点信息 也可以进行动态修改信息

  1. server.port=8888
  2. user.admin.username=admin
  3. user.admin.password=admin

访问 192.168.19.128:8888
image.png

image.png

image.png