数据库-分库分表-简单示例

配置示例

spring:
  application:
    name: app
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://ip:13306/mall-goods
    username: root
    password: njnu@liyong
  jpa:
    database: mysql
    hibernate:
      ddl-auto: none
    show-sql: true
  shardingsphere:
    mode:
      overwrite: true
      repository:
        type: JDBC
      type: Standalone
    # 数据源配置
    datasource:
      # 数据源名称,多数据源以逗号分隔
      db0:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://ip:13306/mall_0
        username: root
        password: njnu@liyong
      db1:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://ip:23306/mall_1
        username: root
        password: njnu@liyong
      names: db0,db1
    # 分片规则配置
    rules:
      sharding:
        # 分片算法配置
        sharding-algorithms:
          database-inline:
            # 分片算法类型
            type: INLINE
            props:
              # 分片算法的行表达式(算法自行定义,此处为方便演示效果)
              algorithm-expression: db$->{user_id % 2}
          table-inline:
            # 分片算法类型
            type: INLINE
            props:
              # 分片算法的行表达式
              algorithm-expression: t_order_$->{order_id % 2}
        tables:
          # 逻辑表名称
          t_order:
            keyGenerateStrategy:
              column: order_id
              key-generator-name: snowflake
            # 行表达式标识符可以使用 ${...} 或 $->{...},但前者与 Spring 本身的属性文件占位符冲突,因此在 Spring 环境中使用行表达式标识符建议使用 $->{...}
            actual-data-nodes: db${0..1}.t_order_${0..1}
            # 分库策略
            database-strategy:
              standard:
                # 分片列名称
                sharding-column: user_id
                # 分片算法名称
                sharding-algorithm-name: database-inline
            # 分表策略
            table-strategy:
              standard:
                # 分片列名称
                sharding-column: order_id
                # 分片算法名称
                sharding-algorithm-name: table-inline
        #如果不配置key-generators会有错误 Caused by: java.lang.IllegalStateException: Can not find keyGenerator xxx in database logic_db .
        key-generators:
          snowflake:
            type: SNOWFLAKE
    # 属性配置
    props:
      # 展示修改以后的sql语句
      sql-show: true

依赖如下:

<groupId>org.apache.shardingsphere</groupId>
    <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
    <version>5.2.1</version>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值