ShardingSphere原理分析和实战总结(二)

简介: ShardingSphere原理分析和实战总结

调用代码

public void createOrder(Order order) {
   order.setId(Long.valueOf(keyGenerator.generateKey().toString()));
   order.setCreateTime(new Date());
   orderMapper.createOrder(order);
}

定时任务(每月执行一次)

CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_create_order`()
BEGIN
declare str_date varchar(16);
SET str_date = date_format(date_add(NOW(), interval 1 MONTH),"%Y%m");
SET @sqlcmd1 = CONCAT('CREATE TABLE  t_order_',str_date
,"  (
  `id` bigint(32) NOT NULL,
  `order_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;");
PREPARE p1 FROM @sqlcmd1;
EXECUTE p1;
DEALLOCATE PREPARE p1;
END

效果图

插入数据时基于雪花算法生成唯一主键

import com.google.common.base.Preconditions;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.strategy.keygen.TimeService;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.unit.DataUnit;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import static java.time.temporal.TemporalAdjusters.firstDayOfMonth;
@Component
public final class KeyGenerator implements ShardingKeyGenerator {
    public KeyGenerator() {
    }
    public static final long EPOCH;
    private static final long SEQUENCE_BITS = 12L;
    private static final long WORKER_ID_BITS = 10L;
    private static final long SEQUENCE_MASK = (1 << SEQUENCE_BITS) - 1;
    private static final long WORKER_ID_LEFT_SHIFT_BITS = SEQUENCE_BITS;
    private static final long TIMESTAMP_LEFT_SHIFT_BITS = WORKER_ID_LEFT_SHIFT_BITS + WORKER_ID_BITS;
    private static final long WORKER_ID_MAX_VALUE = 1L << WORKER_ID_BITS;
    private static final long WORKER_ID = 0;
    private static final int MAX_TOLERATE_TIME_DIFFERENCE_MILLISECONDS = 1;
    @Setter
    private static TimeService timeService = new TimeService();
    @Getter
    @Setter
    private Properties properties = new Properties();
    private byte sequenceOffset;
    private long sequence;
    private long lastMilliseconds;
    @Value("${keyGenerator.snowflake.worker.id}")
    private String workerId;
    @Value("${max.tolerate.time.difference.milliseconds}}")
    private String maxTolerateTime;
    static {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2016, Calendar.NOVEMBER, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        EPOCH = calendar.getTimeInMillis();
    }
    @Override
    public String getType() {
        return "THISSNOWFLAKEY";
    }
    @Override
    public synchronized Comparable<?> generateKey() {
        long currentMilliseconds = timeService.getCurrentMillis();
        if (waitTolerateTimeDifferenceIfNeed(currentMilliseconds)) {
            currentMilliseconds = timeService.getCurrentMillis();
        }
        if (lastMilliseconds == currentMilliseconds) {
            if (0L == (sequence = (sequence + 1) & SEQUENCE_MASK)) {
                currentMilliseconds = waitUntilNextTime(currentMilliseconds);
            }
        } else {
            vibrateSequenceOffset();
            sequence = sequenceOffset;
        }
        lastMilliseconds = currentMilliseconds;
        return ((currentMilliseconds - EPOCH) << TIMESTAMP_LEFT_SHIFT_BITS) | (getWorkerId() << WORKER_ID_LEFT_SHIFT_BITS) | sequence;
    }
    public synchronized long generatorKey() {
        return this.generateKeyByMillis(timeService.getCurrentMillis()).longValue();
    }
    public synchronized Number generateKeyByMillis(long currentMilliseconds) {
        if (lastMilliseconds == currentMilliseconds) {
            if (0L == (sequence = (sequence + 1) & SEQUENCE_MASK)) {
                currentMilliseconds = waitUntilNextTime(currentMilliseconds);
            }
        } else {
            vibrateSequenceOffset();
            sequence = sequenceOffset;
        }
        lastMilliseconds = currentMilliseconds;
        return ((currentMilliseconds - EPOCH) << TIMESTAMP_LEFT_SHIFT_BITS) | (this.getWorkerId() << WORKER_ID_LEFT_SHIFT_BITS) | sequence;
    }
    @SneakyThrows
    private boolean waitTolerateTimeDifferenceIfNeed(final long currentMilliseconds) {
        if (lastMilliseconds <= currentMilliseconds) {
            return false;
        }
        long timeDifferenceMilliseconds = lastMilliseconds - currentMilliseconds;
        Preconditions.checkState(timeDifferenceMilliseconds < getMaxTolerateTimeDifferenceMilliseconds(),
                "Clock is moving backwards, last time is %d milliseconds, current time is %d milliseconds", lastMilliseconds, currentMilliseconds);
        Thread.sleep(timeDifferenceMilliseconds);
        return true;
    }
    private long getWorkerId() {
//        long result = Long.valueOf(properties.getProperty("worker.id", String.valueOf(GenericTool.getWorkId())));
        long result = Long.valueOf(workerId);
        Preconditions.checkArgument(result >= 0L && result < WORKER_ID_MAX_VALUE);
        return result;
    }
    private int getMaxTolerateTimeDifferenceMilliseconds() {
//        return Integer.valueOf(properties.getProperty("max.tolerate.time.difference.milliseconds",
//                String.valueOf(MAX_TOLERATE_TIME_DIFFERENCE_MILLISECONDS)));
        return Integer.valueOf(maxTolerateTime);
    }
    private long waitUntilNextTime(final long lastTime) {
        long result = timeService.getCurrentMillis();
        while (result <= lastTime) {
            result = timeService.getCurrentMillis();
        }
        return result;
    }
    private void vibrateSequenceOffset() {
        sequenceOffset = (byte) (~sequenceOffset & 1);
    }
}

如何查询

1.询时能指定分片键的要尽量指定分片键,sharding-jdbc会自动帮你定位到对应的分表。

2.单分表查询,要指定分片键的,自己手动指定具体的分表先过滤出符合条件的数据,再union all其他分表符合条件的数据。union all的分表最好不要超过2张,即查询时间跨度在两个月内。

    <select id="selectListByProductSelective" parameterType="hashmap" resultMap="ResultMapWithBLOBs">
        select
        <include refid="Base_Column_List"/>
        ,
        <include refid="Blob_Column_List"/>
        from ${startTable}
        <include refid="selectWhere"/>
        <if test="endTable != null ">
            union all
            select
            <include refid="Base_Column_List"/>
            ,
            <include refid="Blob_Column_List"/>
            from ${endTable}
            <include refid="selectWhere"/>
        </if>
        <if test="pageStart != null and pageEnd!=null ">
            limit #{pageStart},#{pageEnd}
        </if>
    </select>

3.多分表关联查询时一定要单独指定每张分表的分片键的值(避免扫描多余的表)。

spring.shardingsphere.datasource.names=test
spring.shardingsphere.datasource.test.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.test.filters=stat,wall,log4j
spring.shardingsphere.datasource.test.stat-view-servlet.enabled=true
spring.shardingsphere.datasource.test.stat-view-servlet.reset-enable=false
spring.shardingsphere.datasource.test.stat-view-servlet.url-pattern=/druid/*
spring.shardingsphere.datasource.test.testOnBorrow=false
spring.shardingsphere.datasource.test.testOnReturn=false
spring.shardingsphere.datasource.testn.testWhileIdle=true
spring.shardingsphere.datasource.test.maxActive=20
spring.shardingsphere.datasource.test.maxWait=20000
spring.shardingsphere.datasource.testn.initial-size=1
spring.shardingsphere.datasource.test.min-idle=2
spring.shardingsphere.datasource.test.timeBetweenEvictionRunsMillis=60000
spring.shardingsphere.datasource.test.minEvictableIdleTimeMillis=300000
spring.shardingsphere.datasource.test.removeAbandoned=true
spring.shardingsphere.datasource.test.removeAbandonedTimeout=180
spring.shardingsphere.datasource.test.maxPoolPreparedStatementPerConnectionSize=50
spring.shardingsphere.datasource.test.poolPreparedStatements=true
spring.shardingsphere.datasource.test.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.test.url=jdbc:mysql://xxx:3306/database?useSSL=false&characterEncoding=utf-8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
spring.shardingsphere.datasource.test.username=xxx
spring.shardingsphere.datasource.test.password=xxx
spring.shardingsphere.datasource.test.validationQuery=SELECT 1 FROM DUAL
spring.shardingsphere.datasource.test.web-stat-filter.enabled=true
spring.shardingsphere.datasource.test.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
spring.shardingsphere.props.sql.show=false
spring.shardingsphere.sharding.tables.defendant.actual-data-nodes = test.defendant_$->{1..5}
spring.shardingsphere.sharding.tables.defendant.table-strategy.inline.sharding-column = case_id
spring.shardingsphere.sharding.tables.defendant.table-strategy.inline.algorithm-expression=defendant_$->{case_id%5 + 1}
spring.shardingsphere.sharding.tables.defendant_business.actual-data-nodes = test.defendant_business_$->{1..5}
spring.shardingsphere.sharding.tables.defendant_business.table-strategy.inline.sharding-column = case_id
spring.shardingsphere.sharding.tables.defendant_business.table-strategy.inline.algorithm-expression=defendant_business_$->{case_id%5 + 1}

case_id是defendant和defendant_business的分片键查询语句如下:

SELECT
  a.*,
  b.* FROM  defendant  a LEFT JOIN  defendant_business b ON a.case_id = b.case_id 
  AND a.case_id = 1 
  AND b.case_id = 1
目录
相关文章
|
人工智能 IDE Java
AI Coding实践:CodeFuse + prompt 从系分到代码
在蚂蚁国际信贷业务系统建设过程中,技术团队始终面临双重考验:一方面需应对日益加速的需求迭代周期,满足严苛的代码质量规范与金融安全合规要求;另一方面,跨地域研发团队的协同效率与代码标准统一性,在传统开发模式下逐渐显现瓶颈。为突破效率制约、提升交付质量,我们积极探索人工智能辅助代码生成技术(AI Coding)的应用实践。本文基于蚂蚁国际信贷技术团队近期的实际项目经验,梳理AI辅助开发在金融级系统快速迭代场景中的实施要点并分享阶段性实践心得。
2535 25
AI Coding实践:CodeFuse + prompt 从系分到代码
|
消息中间件 SQL 分布式计算
一篇文章搞定数据同步工具SeaTunnel
一篇文章搞定数据同步工具SeaTunnel
10866 1
|
6月前
Trae关闭后,自动重新安装问题解决
本方案指导用户将Trae更新模式设为手动:进入设置→Editor设置→应用程序→更新,选择Manual模式。配图清晰展示各操作步骤界面,助您轻松完成配置
1215 3
|
8月前
|
人工智能 缓存 API
阿里云百炼Token Plan是什么?阿里云百炼Token Plan团队版全解析:功能、计费、接入与实战配置指南
随着AI智能体与大模型应用的持续普及,阿里云百炼Token Plan团队版将不断扩展模型生态、优化工具适配、提升服务性能,为企业与开发者提供更稳定、更高效、更经济的AI大模型服务能力。无论是日常AI辅助办公、研发编码,还是构建自主智能体,Token Plan团队版都能提供可靠支撑,助力用户释放AI生产力,实现高效协作与创新。
1207 0
|
SQL 算法 Java
(二十六)MySQL分库篇:Sharding-Sphere分库分表框架的保姆级教学!
前面《MySQL主从原理篇》、《MySQL主从实践篇》两章中聊明白了MySQL主备读写分离、多主多写热备等方案,但如果这些高可用架构依旧无法满足业务规模,或业务增长的需要,此时就需要考虑选用分库分表架构。
8397 4
|
存储 SQL 算法
搞定了 6 种分布式ID,分库分表哪个适合做主键?
在《ShardingSphere5.x分库分表原理与实战》系列的第七篇文章中,作者探讨了分布式ID在分库分表中的重要性,以及如何利用`ShardingSphere-jdbc`的多种主键生成策略。文章介绍了`UUID`、`NanoID`、自定义雪花算法和`CosId`等策略的优缺点,并警告不要在SQL中手动拼接主键字段。此外,文章还展示了如何配置这些策略,并提醒读者`CosId`在5.2.0版本可能不可用。最后,文章讨论了如何自定义分布式主键生成算法,并强调选择策略时要考虑全局唯一性、性能和易用性。
1873 122
|
Linux API C语言
FFmpeg开发笔记(一)搭建Linux系统的开发环境
本文指导初学者如何在Linux上搭建FFmpeg开发环境。首先,由于FFmpeg依赖第三方库,可以免去编译源码的复杂过程,直接安装预编译的FFmpeg动态库。推荐网站<https://github.com/BtbN/FFmpeg-Builds/releases>提供适用于不同系统的FFmpeg包。但在安装前,需确保系统有不低于2.22版本的glibc库。详细步骤包括下载glibc-2.23源码,配置、编译和安装。接着,下载Linux版FFmpeg安装包,解压至/usr/local/ffmpeg,并设置环境变量。最后编写和编译简单的C或C++测试程序验证FFmpeg环境是否正确配置。
1488 8
FFmpeg开发笔记(一)搭建Linux系统的开发环境
|
SQL 存储 算法
SpringBoot整合ShardingSphere实现分表分库&读写分离&读写分离+数据库分表
SpringBoot整合ShardingSphere实现分表分库&读写分离&读写分离+数据库分表
3860 0
SpringBoot整合ShardingSphere实现分表分库&读写分离&读写分离+数据库分表
sharding-jdbc 兼容 MybatisPlus的动态数据源
【8月更文挑战第2天】要使 `Sharding-JDBC` 与 `MyBatisPlus` 的动态数据源兼容,需引入相关依赖,配置数据源及分库分表策略,并在 `MyBatisPlus` 中设置参数以协同工作。可能还需自定义代码处理数据源切换。示例代码框架展示整合方式,实际应用中需按具体业务场景详细配置并处理异常情况,如数据一致性问题。
1188 1
|
Java 数据库连接 测试技术
SpringBoot 3.3.2 + ShardingSphere 5.5 + Mybatis-plus:轻松搞定数据加解密,支持字段级!
【8月更文挑战第30天】在数据驱动的时代,数据的安全性显得尤为重要。特别是在涉及用户隐私或敏感信息的应用中,如何确保数据在存储和传输过程中的安全性成为了开发者必须面对的问题。今天,我们将围绕SpringBoot 3.3.2、ShardingSphere 5.5以及Mybatis-plus的组合,探讨如何轻松实现数据的字段级加解密,为数据安全保驾护航。
1735 1