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
- 先把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配置
- 如下配置,分表最重要的是
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