分布式主键 Distributed Key Generating Algorithm definition

 

 

Data Sharding :: ShardingSphere https://shardingsphere.apache.org/document/current/en/dev-manual/sharding/

KeyGenerateAlgorithm

Fully-qualified class name

org.apache.shardingsphere.keygen.core.algorithm.KeyGenerateAlgorithm

Definition

Distributed Key Generating Algorithm definition

Implementation classes

Configuration TypeDescriptionFully-qualified class name
SNOWFLAKE Snowflake key generate algorithm org.apache.shardingsphere.keygen.snowflake.algorithm.SnowflakeKeyGenerateAlgorithm
UUID UUID key generate algorithm org.apache.shardingsphere.keygen.uuid.algorithm.UUIDKeyGenerateAlgorithm

 

shardingsphere/infra/algorithm/key-generator/type/snowflake/src/main/java/org/apache/shardingsphere/keygen/snowflake/algorithm/SnowflakeKeyGenerateAlgorithm.java at master · apache/shardingsphere · GitHub https://github.com/apache/shardingsphere/blob/master/infra/algorithm/key-generator/type/snowflake/src/main/java/org/apache/shardingsphere/keygen/snowflake/algorithm/SnowflakeKeyGenerateAlgorithm.java

private final AtomicLong lastMillis = new AtomicLong();

 

private synchronized Long generateKey() {
long currentMillis = timeService.getCurrentMillis();
if (waitTolerateTimeDifferenceIfNeed(currentMillis)) {
currentMillis = timeService.getCurrentMillis();
}
if (lastMillis.get() == currentMillis) {
sequence.set(sequence.incrementAndGet() & SEQUENCE_MASK);
if (0L == sequence.get()) {
currentMillis = waitUntilNextTime(currentMillis);
}
} else {
vibrateSequenceOffset();
sequence.set(sequenceOffset.get());
}
lastMillis.set(currentMillis);
return ((currentMillis - EPOCH) << TIMESTAMP_LEFT_SHIFT_BITS) | ((long) getWorkerId() << WORKER_ID_LEFT_SHIFT_BITS) | sequence.get();
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

核心概念 :: ShardingSphere https://shardingsphere.apache.org/document/current/cn/features/sharding/concept/

 

分布式主键

传统数据库软件开发中,主键自动生成技术是基本需求。而各个数据库对于该需求也提供了相应的支持,比如 MySQL 的自增键,Oracle 的自增序列等。 数据分片后,不同数据节点生成全局唯一主键是非常棘手的问题。同一个逻辑表内的不同实际表之间的自增键由于无法互相感知而产生重复主键。 虽然可通过约束自增主键初始值和步长的方式避免碰撞,但需引入额外的运维规则,使解决方案缺乏完整性和可扩展性。

目前有许多第三方解决方案可以完美解决这个问题,如 UUID 等依靠特定算法自生成不重复键,或者通过引入主键生成服务等。为了方便用户使用、满足不同用户不同使用场景的需求, Apache ShardingSphere 不仅提供了内置的分布式主键生成器,例如 UUID、SNOWFLAKE,还抽离出分布式主键生成器的接口,方便用户自行实现自定义的自增主键生成器。

 

 

 

 

 

 

 

 

 

posted @ 2023-12-06 23:20  papering  阅读(35)  评论(0编辑  收藏  举报