Spring Boot integrates ShardingSphere sharding tool AutoTable (2) - example of automatic sharding algorithm | Spring Cloud 46

I. Introduction

In the previous we have a basic understanding ShardingSphereof through the following chapters :AutoTable

Spring Boot integrates ShardingSphere fragmentation tool AutoTable (1) - simple experience | Spring Cloud 45

Continuing from the previous chapter, this chapter AutoTableexplains the supported automatic sharding algorithms one by one with examples.

2. Example construction

The examples are built in an springbootintegrated shardingsphere-jdbcway.

2.1 Overall project structure

insert image description here

2.2 Maven dependencies

shading-sphere/shading-auto-tables-algorithm/pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>shading-sphere</artifactId>
        <groupId>com.gm</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>shading-algorithm</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
            <version>5.2.1</version>
        </dependency>

        <!-- 解决Mybatis中LocalDateTime和SQL中datetime的交互 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-typehandlers-jsr310</artifactId>
            <version>1.0.2</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.33</version>
        </dependency>
        
    </dependencies>

</project>
  • shardingsphere-jdbc-core-spring-boot-starteruse version5.2.1

  • JDBCThe ORMframe selectionmybatis-plus

2.3 Configuration file

server:
  port: 8844

spring:
  application:
    name: @artifactId@
  shardingsphere:
    # 数据源配置
    datasource:
      names: ds1,ds2
      ds1:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://192.168.0.35:3306/db1?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true&allowMultiQueries=true&serverTimezone=Asia/Shanghai
        username: root
        password: '1qaz@WSX'
      ds2:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://192.168.0.46:3306/db2?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true&allowMultiQueries=true&serverTimezone=Asia/Shanghai
        username: root
        password: '1qaz@WSX'

    # 定义规则
    rules:
      sharding:
        # 采用自动分片算法
        autoTables:

The above configuration is the common basic configuration of each automatic sharding algorithm.

3. Automatic Fragmentation Algorithm

AutoTableSupports all automatic sharding algorithms, including:

  • MOD: Modulus sharding algorithm
  • HASH_MOD: Hash modulo sharding algorithm
  • VOLUME_RANGE: Range sharding algorithm based on shard capacity
  • BOUNDARY_RANGE: Range Fragmentation Algorithm Based on Fragmentation Boundaries
  • AUTO_INTERVAL: Automatic Time Segment Sharding Algorithm

3.1 Modulo - MOD

Similar MySQLto PATITIONthe one in MOD, ShardingSpherethe actual number of tables is automatically calculated by the number of shards and the denominator of the modulus.

Configurable properties:

attribute name type of data illustrate
sharding-count int Number of fragments

3.1.1 Examples

This example actually requires 2two data sources (single data source scenario is also supported), each data source has 3a t_auto_order_modsub-table, and the sub-table format is:t_auto_order_mod_${0..5}

3.1.1.1 Automatic Fragmentation Algorithm Configuration

        # 采用自动分片算法
        autoTables:
          # 取模
          t_auto_order_mod:
            actualDataSources: ds$->{
    
    1..2}
            sharding-strategy:
              standard:
                sharding-column: order_id
                sharding-algorithm-name: auto_order_mod
            # 分布式序列策略
            key-generate-strategy:
              # 自增列名称,缺省表示不使用自增主键生成器
              column: order_id
              # 分布式序列算法名称
              key-generator-name: snowflake
        # 分片算法配置
        sharding-algorithms:
          # 取模
          auto_order_mod:
            type: MOD
            props:
              sharding-count: 6              

3.1.1.2 Entity class

com/gm/shading/auto/tables/algorithm/entity/AutoOrderMod.java

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;

@Data
@TableName("t_auto_order_mod")
public class AutoOrderMod {
    
    

    @TableId(type = IdType.ASSIGN_ID)
    private Long orderId;
    private BigDecimal price;
    private Long userId;
    private String status;
}

3.1.1.3 Mapper

com/gm/shading/auto/tables/algorithm/mapper/AutoOrderModMapper.java

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gm.shading.auto.tables.algorithm.entity.AutoOrderMod;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface AutoOrderModMapper extends BaseMapper<AutoOrderMod> {
    
    
    void save(AutoOrderMod autoOrder);
}

src/main/resources/mapper/AutoOrderModMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.gm.shading.auto.tables.algorithm.mapper.AutoOrderModMapper">
    <insert id="save" parameterType="com.gm.shading.auto.tables.algorithm.entity.AutoOrderMod">
        insert into t_auto_order_mod (price, user_id, status)
        values (#{price}, #{userId}, #{status})
    </insert>
</mapper>

3.1.1.4 Unit testing

com/gm/shading/auto/tables/algorithm/ShadingAutoTablesAlgorithmApplicationTests.java

    @Autowired
    AutoOrderModMapper autoOrderModMapper;
    
    @Autowired
    JdbcTemplate jdbcTemplate; 
    
    @Test
    public void testCreateAutoOrderMod() {
    
    
        jdbcTemplate.execute("CREATE TABLE `t_auto_order_mod` (\n" +
                " `order_id` bigint(20) NOT NULL COMMENT '订单id',\n" +
                " `price` decimal(10,2) NOT NULL COMMENT '订单价格',\n" +
                " `user_id` bigint(20) NOT NULL COMMENT '下单用户id',\n" +
                " `status` varchar(50) NOT NULL COMMENT '订单状态',\n" +
                " PRIMARY KEY (`order_id`) USING BTREE\n" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;");
    }

    @Test
    public void testInsertAutoOrderMod() {
    
    
        Random random = new Random();
        for (int i = 1; i < 10; i++) {
    
    
            AutoOrderMod order = new AutoOrderMod();
            order.setPrice(new BigDecimal(i));
            order.setUserId(Integer.valueOf(random.nextInt(25)).longValue());
            order.setStatus(i + "");
            autoOrderModMapper.save(order);
        }
    }

3.2 Hash modulus - HASH_MOD

MODModulo is usually a fragmentation of numeric types, HASH_MODnot only for numerical values, but also for character (通过hash值取模)columns for fragmentation. The algorithm is basically and MODsimilar.

Configurable properties:

attribute name type of data illustrate
sharding-count int Number of fragments

3.2.1 Examples

In this case, there is only one data source, and there are sub- tables 6in the data source , and the actual table is obtained by modulo calculation according to the value of . The table format is:t_auto_order_hash_modorder_idhasht_auto_order_hash_mod_${0..5}

3.2.1.1 Automatic Fragmentation Algorithm Configuration

        # 采用自动分片算法
        autoTables:
          # 散列取模
          t_auto_order_hash_mod:
            actualDataSources: ds1
            sharding-strategy:
              standard:
                sharding-column: order_id
                sharding-algorithm-name: auto_order_hash_mod
            # 分布式序列策略
            key-generate-strategy:
              # 自增列名称,缺省表示不使用自增主键生成器
              column: order_id
              # 分布式序列算法名称
              key-generator-name: snowflake
        # 分片算法配置
        sharding-algorithms:
          # 散列取模
          auto_order_hash_mod:
            type: HASH_MOD
            props:
              sharding-count: 6              

3.2.1.2 Entity class

com/gm/shading/auto/tables/algorithm/entity/AutoOrderHashMod.java

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;

@Data
@TableName("t_auto_order_hash_mod")
public class AutoOrderHashMod {
    
    

    @TableId(type = IdType.ASSIGN_ID)
    private Long orderId;
    private BigDecimal price;
    private Long userId;
    private String status;
}

3.2.1.3 Mapper

com/gm/shading/auto/tables/algorithm/mapper/AutoOrderHashModMapper.java

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gm.shading.auto.tables.algorithm.entity.AutoOrderHashMod;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface AutoOrderHashModMapper extends BaseMapper<AutoOrderHashMod> {
    
    
    void save(AutoOrderHashMod autoOrder);
}

src/main/resources/mapper/AutoOrderHashModMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.gm.shading.auto.tables.algorithm.mapper.AutoOrderHashModMapper">
    <insert id="save" parameterType="com.gm.shading.auto.tables.algorithm.entity.AutoOrderHashMod">
        insert into t_auto_order_hash_mod (price, user_id, status)
        values (#{price}, #{userId}, #{status})
    </insert>
</mapper>

3.2.1.4 Unit testing

com/gm/shading/auto/tables/algorithm/ShadingAutoTablesAlgorithmApplicationTests.java

    @Autowired
    AutoOrderHashModMapper autoOrderHashModMapper;
    
    @Autowired
    JdbcTemplate jdbcTemplate; 

    @Test
    public void testCreateAutoOrderHashMod() {
    
    
        jdbcTemplate.execute("CREATE TABLE `t_auto_order_hash_mod` (\n" +
                " `order_id` bigint(20) NOT NULL COMMENT '订单id',\n" +
                " `price` decimal(10,2) NOT NULL COMMENT '订单价格',\n" +
                " `user_id` bigint(20) NOT NULL COMMENT '下单用户id',\n" +
                " `status` varchar(50) NOT NULL COMMENT '订单状态',\n" +
                " PRIMARY KEY (`order_id`) USING BTREE\n" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;");
    }

    @Test
    public void testInsertAutoOrderHashMod() {
    
    
        Random random = new Random();
        for (int i = 1; i < 10; i++) {
    
    
            AutoOrderHashMod order = new AutoOrderHashMod();
            order.setPrice(new BigDecimal(i));
            order.setUserId(Integer.valueOf(random.nextInt(25)).longValue());
            order.setStatus(i + "");
            autoOrderHashModMapper.save(order);
        }
    }

3.3 Capacity range - VOLUME_RANGE

The algorithm will calculate the actual number of shards according (${range-upper} - ${range-lower}) / ${sharding-volume} + 2to , so as to realize the automatic sharding function.

Configurable properties:

attribute name type of data illustrate
range-lower long The lower bound of the range, if the data exceeds the bounds, an error will be reported
range-upper long The upper bound of the range, data beyond the bounds will report an error
sharding-volume long Fragment capacity

It should be noted that the reason why this algorithm + 2actually contains two hidden tables:

  • store data less range-lowerthan
  • store data larger range-upperthan

3.3.1 Examples

This example actually requires 2data sources, and each data source 2has t_auto_order_volume_rangesub-tables, and the actual table is calculated according priceto the capacity range of . The table format is:t_auto_order_volume_range_${0..3}

3.3.1.1 Automatic Fragmentation Algorithm Configuration

        # 采用自动分片算法
        autoTables:
          # 容量范围
          t_auto_order_volume_range:
            actualDataSources: ds$->{
    
    1..2}
            sharding-strategy:
              standard:
                sharding-column: price
                sharding-algorithm-name: auto_order_volume_range
            # 分布式序列策略
            key-generate-strategy:
              # 自增列名称,缺省表示不使用自增主键生成器
              column: order_id
              # 分布式序列算法名称
              key-generator-name: snowflake
        # 分片算法配置
        sharding-algorithms:
          # 容量范围
          auto_order_volume_range:
            type: VOLUME_RANGE
            props:
              range-lower: 0
              range-upper: 20000
              sharding-volume: 10000              

That is, the above example contains ((20000 - 0) / 10000 + 2) = 4shards:

db1: 
  - t_auto_order_volume_range_0: (-∞..0) 
  - t_auto_order_volume_range_2: [10000..20000) 
db2:
  - t_auto_order_volume_range_1: [0..10000) 
  - t_auto_order_volume_range_3: [20000..+∞)

3.3.1.2 Entity class

com/gm/shading/auto/tables/algorithm/entity/AutoOrderVolumeRange.java

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;

@Data
@TableName("t_auto_order_volume_range")
public class AutoOrderVolumeRange {
    
    

    @TableId(type = IdType.ASSIGN_ID)
    private Long orderId;
    private BigDecimal price;
    private Long userId;
    private String status;
}

3.3.1.3 Mapper

com/gm/shading/auto/tables/algorithm/mapper/AutoOrderVolumeRangeMapper.java

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gm.shading.auto.tables.algorithm.entity.AutoOrderVolumeRange;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface AutoOrderVolumeRangeMapper extends BaseMapper<AutoOrderVolumeRange> {
    
    
    void save(AutoOrderVolumeRange autoOrder);
}

src/main/resources/mapper/AutoOrderVolumeRangeMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.gm.shading.auto.tables.algorithm.mapper.AutoOrderVolumeRangeMapper">
    <insert id="save" parameterType="com.gm.shading.auto.tables.algorithm.entity.AutoOrderVolumeRange">
        insert into t_auto_order_volume_range (price, user_id, status)
        values (#{price}, #{userId}, #{status})
    </insert>
</mapper>

3.3.1.4 Unit testing

com/gm/shading/auto/tables/algorithm/ShadingAutoTablesAlgorithmApplicationTests.java

    @Autowired
    AutoOrderVolumeRangeMapper autoOrderVolumeRangeMapper;
    
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Test
    public void testCreateAutoOrderVolumeRange() {
    
    
        jdbcTemplate.execute("CREATE TABLE `t_auto_order_volume_range` (\n" +
                " `order_id` bigint(20) NOT NULL COMMENT '订单id',\n" +
                " `price` decimal(10,2) NOT NULL COMMENT '订单价格',\n" +
                " `user_id` bigint(20) NOT NULL COMMENT '下单用户id',\n" +
                " `status` varchar(50) NOT NULL COMMENT '订单状态',\n" +
                " PRIMARY KEY (`order_id`) USING BTREE\n" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;");
    }
    
    @Test
    public void testInsertAutoOrderVolumeRange() {
    
    
        Random random = new Random();
        for (int i = 1; i < 10; i++) {
    
    
            AutoOrderVolumeRange order = new AutoOrderVolumeRange();
            order.setPrice(new BigDecimal(random.nextInt(20000)));
            order.setUserId(Integer.valueOf(random.nextInt(25)).longValue());
            order.setStatus(i + "");
            autoOrderVolumeRangeMapper.save(order);
        }
    }

3.4 Boundary range - BOUNDARY_RANGE

The algorithm will perform sharding according to the custom range , for example: 0 ~ 100 is in shard 0, 100 ~ 1000 is in shard 1, 1000 ~ 1500 is in shard 2, etc.

Configurable properties:

attribute name type of data illustrate
sharding-ranges String Fragment range, multiple boundaries can be ,separated

Note that there are actually two hidden tables included:

  • Store data that is less than the minimum value of the custom range
  • Store data greater than the maximum value of the custom range

3.4.1 Examples

This example actually requires 2data sources, and each data source 3has t_auto_order_boundary_rangesub-tables, and the actual table is calculated according priceto the custom range of . The table format is:t_auto_order_boundary_range_${0..5}

3.4.1.1 Automatic Fragmentation Algorithm Configuration

        # 采用自动分片算法
        autoTables:
          # 边界范围
          t_auto_order_boundary_range:
            actualDataSources: ds$->{
    
    1..2}
            sharding-strategy:
              standard:
                sharding-column: price
                sharding-algorithm-name: auto_order_boundary_range
            # 分布式序列策略
            key-generate-strategy:
              # 自增列名称,缺省表示不使用自增主键生成器
              column: order_id
              # 分布式序列算法名称
              key-generator-name: snowflake
        # 分片算法配置
        sharding-algorithms:
          # 边界范围
          auto_order_boundary_range:
            type: BOUNDARY_RANGE
            props:
              sharding-ranges: 10,15,100,12000,16000            

The custom scope in this example can be split into:

-∞..10, 
10..15, 
15..100, 
100..12000, 
12000..16000, 
16000..+∞

3.4.1.2 Entity class

com/gm/shading/auto/tables/algorithm/entity/AutoOrderBoundaryRange.java

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;

@Data
@TableName("t_auto_order_boundary_range")
public class AutoOrderBoundaryRange {
    
    

    @TableId(type = IdType.ASSIGN_ID)
    private Long orderId;
    private BigDecimal price;
    private Long userId;
    private String status;
}

3.4.1.3 Mapper

com/gm/shading/auto/tables/algorithm/mapper/AutoOrderBoundaryRangeMapper.java

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gm.shading.auto.tables.algorithm.entity.AutoOrderBoundaryRange;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface AutoOrderBoundaryRangeMapper extends BaseMapper<AutoOrderBoundaryRange> {
    
    
    void save(AutoOrderBoundaryRange autoOrder);
}

src/main/resources/mapper/AutoOrderBoundaryRangeMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.gm.shading.auto.tables.algorithm.mapper.AutoOrderBoundaryRangeMapper">
    <insert id="save" parameterType="com.gm.shading.auto.tables.algorithm.entity.AutoOrderBoundaryRange">
        insert into t_auto_order_boundary_range (price, user_id, status)
        values (#{price}, #{userId}, #{status})
    </insert>
</mapper>

3.4.1.4 Unit testing

com/gm/shading/auto/tables/algorithm/ShadingAutoTablesAlgorithmApplicationTests.java

    @Autowired
    AutoOrderBoundaryRangeMapper autoOrderBoundaryRangeMapper;
    
    @Autowired
    JdbcTemplate jdbcTemplate; 
       
    @Test
    public void testCreateAutoOrderBoundaryRange() {
    
    
        jdbcTemplate.execute("CREATE TABLE `t_auto_order_boundary_range` (\n" +
                " `order_id` bigint(20) NOT NULL COMMENT '订单id',\n" +
                " `price` decimal(10,2) NOT NULL COMMENT '订单价格',\n" +
                " `user_id` bigint(20) NOT NULL COMMENT '下单用户id',\n" +
                " `status` varchar(50) NOT NULL COMMENT '订单状态',\n" +
                " PRIMARY KEY (`order_id`) USING BTREE\n" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;");
    }

    @Test
    public void testInsertAutoOrderBoundaryRange() {
    
    
        Random random = new Random();
        for (int i = 1; i < 10; i++) {
    
    
            AutoOrderBoundaryRange order = new AutoOrderBoundaryRange();
            order.setPrice(new BigDecimal(random.nextInt(20000)));
            order.setUserId(Integer.valueOf(random.nextInt(25)).longValue());
            order.setStatus(i + "");
            autoOrderBoundaryRangeMapper.save(order);
        }
    }

3.5 Automatic date interval - AUTO_INTERVAL

The date interval will be by: 时间开始边界 到 时间结束边界 之间的秒数 除以 分片秒数 再加 2, thus calculating the total number of shards. That is ({datetime-upper} - {datetime-lower}) / sharding-seconds + 2.

Configurable properties:

attribute name type of data illustrate
datetime-lower String The start time range of the shard, timestamp format: yyyy-MM-dd HH:mm:ss
datetime-upper String The end time range of the shard, timestamp format: yyyy-MM-dd HH:mm:ss
sharding-seconds long The maximum time that can be carried by a single shard, unit: second, the second in the timestamp format of the shard key is allowed to have time precision, but the time precision after the second will be automatically erased

It should be noted that the reason why this algorithm + 2actually contains two hidden tables:

  • store data less datetime-lowerthan
  • store data larger datetime-upperthan

3.5.1 Examples

This example actually requires 2data sources and a total 5of t_auto_order_auto_intervalsub-tables, create_timeand the actual table is obtained by calculating the maximum time that the sub-shards can carry . The table format is:t_auto_order_auto_interval_${0..4}

3.5.1.1 Automatic Fragmentation Algorithm Configuration

        # 采用自动分片算法
        autoTables:
          # 自动日期间隔
          t_auto_order_auto_interval:
            actualDataSources: ds$->{
    
    1..2}
            sharding-strategy:
              standard:
                sharding-column: create_time
                sharding-algorithm-name: auto_order_auto_interval
            # 分布式序列策略
            key-generate-strategy:
              # 自增列名称,缺省表示不使用自增主键生成器
              column: order_id
              # 分布式序列算法名称
              key-generator-name: snowflake
        # 分片算法配置
        sharding-algorithms:
          # 自动日期间隔
          auto_order_auto_interval:
            type: AUTO_INTERVAL
            props:
              datetime-lower: 2023-05-07 00:00:00
              datetime-upper: 2023-05-10 00:00:00
              sharding-seconds: 86400           

In this example it would be parsed as:

?, 2023-05-07 00:00:00 = 0
2023-05-07 00:00:00, 2023-05-08 00:00:00 = 1
2023-05-08 00:00:00, 2023-05-09 00:00:00 = 2
2023-05-09 00:00:00, 2023-05-10 00:00:00 = 3
2023-05-10 00:00:00, ? = 4

3.5.1.2 Entity class

com/gm/shading/auto/tables/algorithm/entity/AutoOrderBoundaryRange.java

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;

@Data
@TableName("t_auto_order_auto_interval")
public class AutoOrderAutoInterval {
    
    

    @TableId(type = IdType.ASSIGN_ID)
    private Long orderId;
    private BigDecimal price;
    private Long userId;
    private String status;
    private LocalDateTime createTime;
}

3.5.1.3 Mapper

com/gm/shading/auto/tables/algorithm/mapper/AutoOrderAutoIntervalMapper.java

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gm.shading.auto.tables.algorithm.entity.AutoOrderAutoInterval;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface AutoOrderAutoIntervalMapper extends BaseMapper<AutoOrderAutoInterval> {
    
    
    void save(AutoOrderAutoInterval autoOrder);
}

src/main/resources/mapper/AutoOrderAutoIntervalMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.gm.shading.auto.tables.algorithm.mapper.AutoOrderAutoIntervalMapper">
    <insert id="save" parameterType="com.gm.shading.auto.tables.algorithm.entity.AutoOrderAutoInterval">
        insert into t_auto_order_auto_interval (price, user_id, status,create_time)
        values (#{price}, #{userId}, #{status}, #{createTime})
    </insert>
</mapper>

3.5.1.4 Unit testing

com/gm/shading/auto/tables/algorithm/ShadingAutoTablesAlgorithmApplicationTests.java

    @Autowired
    AutoOrderAutoIntervalMapper autoOrderAutoIntervalMapper;

    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @Test
    public void testCreateAutoOrderAutoInterval() {
    
    
        jdbcTemplate.execute("CREATE TABLE `t_auto_order_auto_interval` (\n" +
                " `order_id` bigint(20) NOT NULL COMMENT '订单id',\n" +
                " `price` decimal(10,2) NOT NULL COMMENT '订单价格',\n" +
                " `user_id` bigint(20) NOT NULL COMMENT '下单用户id',\n" +
                " `status` varchar(50) NOT NULL COMMENT '订单状态',\n" +
                " `create_time` datetime NOT NULL COMMENT '订单时间',\n" +
                " PRIMARY KEY (`order_id`) USING BTREE\n" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;");
    }

    @Test
    public void testInsertAutoOrderAutoInterval() {
    
    
        Random random = new Random();
        for (int i = 1; i < 10; i++) {
    
    
            AutoOrderAutoInterval order = new AutoOrderAutoInterval();
            order.setPrice(new BigDecimal(random.nextInt(20000)));
            order.setUserId(Integer.valueOf(random.nextInt(25)).longValue());
            order.setStatus(i + "");
            // 随机减少一定天数再随机增加一定天数
            order.setCreateTime(LocalDateTime.now().minusDays(random.nextInt(10)).plusDays(random.nextInt(10)));
            autoOrderAutoIntervalMapper.save(order);
        }
    }

3.6 source code

For the complete source code of the above example, please see: https://gitee.com/gm19900510/springboot-cloud-example.git

Guess you like

Origin blog.csdn.net/ctwy291314/article/details/130561221