sharding sphere 4.0.0-RC1版本 按年分表实战

1. sharding sphere 4.0.0-RC1版本 按年分表实战

1.1. 需求

需要对日志表进行按时间划分表,由于用于后台系统,日志量预估不会太大,因此按年划分表

经过我不断的查阅sharding sphere资料和实践,我最后还是决定先建表,再把actual-data-nodes表结点给定下来,为什么这么说?

我纠结的是到底要不要动态创建表,若想要不自己手动每隔几年维护表,我们当然希望能自动创建。但经过我的实践,sharding sphere本身没有提供该功能,但可以通过分片算法实现类中自定义实现,但前提是我们要随时知道要分片表有几个分片,比如log_2019,log_2020,log_2021,只要我能初始化的时候知道分片有几个表以及表名,那么我就不会查询到不存在的表导致报错,反之则容易报错

我们知道mysql可以通过查询information_schema.TABLES来查询存在的表,但是不知道是不是sharding sphere的bug,我用库名加表名查该库它会强制给我改写成我默认的连接库,导致表不存在,根本查不到

所以我退而求其次,下面我列出我的方案,方案采用的版本是4.0.0-RC1

1.2. 引入pom

  1. 先把pom列出来,只给代码不给pom都是耍流氓
         <!-- 分库分表 -->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>4.0.0-RC1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-namespace</artifactId>
            <version>4.0.0-RC1</version>
        </dependency>

1.3. application.yml配置

  1. 如下配置,分表最重要的是table-strategy分表策略,sharding-column表示分表字段,当插入查询需要指定哪个分表时,必须带上这个条件,否则可能出错,actual-data-nodes表示你分了哪些表,它有一定语法,如下$->{0..1}表示system_log_2020,system_log_2021两张表,我需要在mysql建好这两张表
spring:
  shardingsphere:
    props:
      sql:
        show: true
    datasource:
      names: ds0
      ds0:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://xxxxx:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT+8&allowMultiQueries=true
        username: xxx
        password: xxx
    sharding:
      tables:
        system_log:
          actual-data-nodes: ds0.system_log_202$->{0..1}
          table-strategy:
            standard:
              sharding-column: created
              precise-algorithm-class-name: com.xxx.platform.system.log.LogShardingAlgorithm
              range-algorithm-class-name: com.xxx.platform.system.log.Lo
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值