ShardingSphere-JDBC学习

佚名 / 2024-01-19 / 原文

springBoot  引入maven

            <dependency>
                <groupId>org.apache.shardingsphere</groupId>
                <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
                <version>4.0.0-RC1</version>
            </dependency>

  

application.yml配置

spring:
  shardingsphere:
    datasource:
      names: db1,db2
      db1:
        url: jdbc:mysql://localhost:3306/db1?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
        username: root
        password: root
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
      db2:
        url: jdbc:mysql://localhost:3306/db2?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
        username: root
        password: root
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
#      masterslave:
#        # 读写分离配置
#        load-balance-algorithm-type: round_robin #负载均衡策略,round_robin是轮循
#        # 最终的数据源名称
#        name: dataSource #就是bean的名字
#        # 主库数据源名称
#        master-data-source-name: db1
#        # 从库数据源名称列表,多个逗号分隔
#        slave-data-source-names: db2
    sharding:
      default-database-strategy:
        inline:
          sharding-column: order_id #数据库分片策略字段
          algorithm-expression: db${order_id % 2+1} # 配置t_order表分表策略
      tables:
        t_order:
          actual-data-nodes: db$->{1..2}.t_order_$->{0..3}  #配置t_order表分库策略(inline-基于行表达式的分片算法)
          table-strategy:
            inline:  #只适合一个字段 
              sharding-column: order_id   #增删改查数据包含order_id找到对应的表
              algorithm-expression: t_order_$->{order_id % 2}
          key-generator:
            column: order_id
            type: SNOWFLAKE
    props:
      sql:
        show: true

  

table-strategy:指定表的分片策略,table-strategy有以下几种策略

none 表示不分片,所有数据都存储在同一个表中。

standard 表示使用标准分片策略,根据分片键的值进行范围匹配,将数据路由到对应的分片表中。

inline 表示使用行表达式分片策略,根据分片键的值通过表达式计算得到分片结果,将数据路由到对应的分片表中。

complex 表示使用复合分片策略,可以同时使用多个分片键对数据进行分片计算,将数据路由到对应的分片表中。