­

CosId 1.1.8 發布,通用、靈活、高性能的分散式 ID 生成器

CosId 通用、靈活、高性能的分散式 ID 生成器

介紹

CosId 旨在提供通用、靈活、高性能的分散式 ID 生成器。 目前提供了三類 ID 生成器:

  • SnowflakeId : 單機 TPS 性能:409W/s JMH 基準測試 , 主要解決 時鐘回撥問題機器號分配問題 並且提供更加友好、靈活的使用體驗。
  • SegmentId : RedisIdSegmentDistributor 單機 TPS 性能(步長 1000) :2950W+/s JMH 基準測試 , 每次獲取一段(Step) ID,來降低號段分發器的網路IO請求頻次提升性能。
  • SegmentChainId : SegmentChainId (lock-free) 是對 SegmentId 的增強,設計圖如下。PrefetchWorker 維護安全距離(safeDistance), 使得 SegmentChainId 達到近似 AtomicLongTPS 性能(步長 1000): 10272W+/s JMH 基準測試

SegmentClainId

更新內容(1.1.8) 🎉 🎉 🎉

  • 優化:新增抽象 IdSegment interface。
  • 增強:優化DefaultSegmentId防禦性校驗後端發號器持久層號段丟失、回滾。
  • 增強:增強IdSegmentDistributor支援批量獲取號段,降低網路ID請求頻次,進一步提升性能。
  • 優化:優化SegmentChainId (lock-free)性能,合理配置的情況下可達到AtomicLong性能級別(10272W+/s JMH JMH 基準測試 )。
  • 新增:添加 IdSegmentDistributor.Mock,模擬發號器網路IO請求,方便測試。
  • 增強:支援通過 spring-boot 配置開啟SegmentChainId 模式(spring-boot-starter-cosid)。
  • 新增:添加LifecycleSegmentChainId優雅關閉 PrefetchWorker  。

SnowflakeId

SnowflakeId

SnowflakeId 使用 Long (64 bits) 位分區來生成 ID 的一種分散式 ID 演算法。
通用的位分配方案為:timestamp (41 bits) + machineId (10 bits) + sequence (12 bits) = 63 bits 。

  • 41 位 timestamp = (1L<<41)/(1000/3600/365) 約可以存儲 69 年的時間戳,即可以使用的絕對時間為 EPOCH + 69 年,一般我們需要自定義 EPOCH 為產品開發時間,另外還可以通過壓縮其他區域的分配位數,來增加時間戳位數來延長可用時間。
  • 10 位 machineId = (1L<<10) = 1024 即相同業務可以部署 1024 個副本 (在 Kubernetes 概念里沒有主從副本之分,這裡直接沿用 Kubernetes 的定義) 實例,一般情況下沒有必要使用這麼多位,所以會根據部署規模需要重新定義。
  • 12 位 sequence = (1L<<12) * 1000 = 4096000 即單機每秒可生成約 409W 的 ID,全局同業務集群可產生 4096000*1024=419430W=41.9億(TPS)。

SnowflakeId 設計上可以看出:

  • 👍 timestamp 在高位,所以 SnowflakeId 是本機單調遞增的,受全局時鐘同步影響 SnowflakeId 是全局趨勢遞增的。
  • 👍 SnowflakeId 不對任何第三方中間件有強依賴關係,並且性能也非常高。
  • 👍 位分配方案可以按照業務系統需要靈活配置,來達到最優使用效果。
  • 👎 強依賴本機時鐘,潛在的時鐘回撥問題會導致 ID 重複。
  • 👎 machineId 需要手動設置,實際部署時如果採用手動分配 machineId,會非常低效。

CosId-SnowflakeId 主要解決 SnowflakeId 倆大問題:機器號分配問題、時鐘回撥問題。 並且提供更加友好、靈活的使用體驗。

MachineIdDistributor (MachineId 分配器)

目前 CosId 提供了以下三種 MachineId 分配器。

ManualMachineIdDistributor

cosid:
  snowflake:
    machine:
      distributor:
        type: manual
        manual:
          machine-id: 0

手動分配 MachineId

StatefulSetMachineIdDistributor

cosid:
  snowflake:
    machine:
      distributor:
        type: stateful_set

使用 KubernetesStatefulSet 提供的穩定的標識 ID 作為機器號。

RedisMachineIdDistributor

RedisMachineIdDistributor

cosid:
  snowflake:
    machine:
      distributor:
        type: redis

使用 Redis 作為機器號的分發存儲。

ClockBackwardsSynchronizer (時鐘回撥同步器)

cosid:
  snowflake:
    clock-backwards:
      spin-threshold: 10
      broken-threshold: 2000

默認提供的 DefaultClockBackwardsSynchronizer 時鐘回撥同步器使用主動等待同步策略,spinThreshold(默認值 10 毫秒) 用於設置自旋等待閾值, 當大於spinThreshold時使用執行緒休眠等待時鐘同步,如果超過brokenThreshold(默認值 2 秒)時會直接拋出ClockTooManyBackwardsException異常。

MachineStateStorage (機器狀態存儲)

public class MachineState {
    public static final MachineState NOT_FOUND = of(-1, -1);
    private final int machineId;
    private final long lastTimeStamp;

    public MachineState(int machineId, long lastTimeStamp) {
        this.machineId = machineId;
        this.lastTimeStamp = lastTimeStamp;
    }

    public int getMachineId() {
        return machineId;
    }

    public long getLastTimeStamp() {
        return lastTimeStamp;
    }

    public static MachineState of(int machineId, long lastStamp) {
        return new MachineState(machineId, lastStamp);
    }
}
cosid:
  snowflake:
    machine:
      state-storage:
        local:
          state-location: ./cosid-machine-state/

默認提供的 LocalMachineStateStorage 本地機器狀態存儲,使用本地文件存儲機器號、最近一次時間戳,用作 MachineState 快取。

ClockSyncSnowflakeId (主動時鐘同步 SnowflakeId)

cosid:
  snowflake:
    share:
      clock-sync: true

默認 SnowflakeId 當發生時鐘回撥時會直接拋出 ClockBackwardsException 異常,而使用 ClockSyncSnowflakeId 會使用 ClockBackwardsSynchronizer主動等待時鐘同步來重新生成 ID,提供更加友好的使用體驗。

SafeJavaScriptSnowflakeId (JavaScript 安全的 SnowflakeId)

SnowflakeId snowflakeId=SafeJavaScriptSnowflakeId.ofMillisecond(1);

JavaScriptNumber.MAX_SAFE_INTEGER 只有 53 位,如果直接將 63 位的 SnowflakeId 返回給前端,那麼會值溢出的情況,通常我們可以將 SnowflakeId 轉換為 String 類型或者自定義 SnowflakeId 位分配來縮短 SnowflakeId 的位數 使 ID 提供給前端時不溢出。

SnowflakeFriendlyId (可以將 SnowflakeId 解析成可讀性更好的 SnowflakeIdState )

cosid:
  snowflake:
    share:
      friendly: true
public class SnowflakeIdState {

    private final long id;

    private final int machineId;

    private final long sequence;

    private final LocalDateTime timestamp;
    /**
     * {@link #timestamp}-{@link #machineId}-{@link #sequence}
     */
    private final String friendlyId;
}
public interface SnowflakeFriendlyId extends SnowflakeId {

    SnowflakeIdState friendlyId(long id);

    SnowflakeIdState ofFriendlyId(String friendlyId);

    default SnowflakeIdState friendlyId() {
        long id = generate();
        return friendlyId(id);
    }
}
        SnowflakeFriendlyId snowflakeFriendlyId=new DefaultSnowflakeFriendlyId(snowflakeId);
        SnowflakeIdState idState=snowflakeFriendlyId.friendlyId();
        idState.getFriendlyId(); //20210623131730192-1-0

SegmentId (號段模式)

RedisIdSegmentDistributor (使用Redis作為號段分發後端存儲)

cosid:
  segment:
    enabled: true
    distributor:
      type: redis
    share:
      offset: 0
      step: 100
    provider:
      bizC:
        offset: 10000
        step: 100
      bizD:
        offset: 10000
        step: 100

RedisIdSegmentDistributor 步長設置為 1 時(每次生成ID都需要執行一次 Redis 網路 IO 請求)TPS 性能約為 21W/s (JMH 基準測試 ),如果在部分場景下我們對 ID 生成的 TPS 性能有更高的要求,那麼可以選擇使用增加每次ID分發步長來降低網路 IO 請求頻次,提高 IdGenerator 性能(比如增加步長為 1000,性能可提升到 3545W+/s JMH 基準測試)。

SegmentChainId (號段鏈模式)

SegmentClainId

cosid:
  segment:
    enabled: true
    mode: chain
    chain:
      safe-distance: 100
      prefetch-period: 4000ns
    distributor:
      type: redis
    share:
      offset: 0
      step: 100
    provider:
      bizC:
        offset: 10000
        step: 100
      bizD:
        offset: 10000
        step: 100

IdGeneratorProvider

cosid:
  snowflake:
    provider:
      bizA:
        #      epoch:
        #      timestamp-bit:
        sequence-bit: 12
      bizB:
        #      epoch:
        #      timestamp-bit:
        sequence-bit: 12
IdGenerator idGenerator=idGeneratorProvider.get("bizA");

在實際使用中我們一般不會所有業務服務使用同一個 IdGenerator ,而是不同的業務使用不同的 IdGenerator,那麼 IdGeneratorProvider 就是為了解決這個問題而存在的,他是 IdGenerator 的容器,可以通過業務名來獲取相應的 IdGenerator

Examples

CosId-Examples

安裝

Gradle

Kotlin DSL

    val cosidVersion = "1.1.8";
    implementation("me.ahoo.cosid:spring-boot-starter-cosid:${cosidVersion}")

Maven

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="//maven.apache.org/POM/4.0.0"
         xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <artifactId>demo</artifactId>
    <properties>
        <cosid.version>1.1.8</cosid.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>me.ahoo.cosid</groupId>
            <artifactId>spring-boot-starter-cosid</artifactId>
            <version>${cosid.version}</version>
        </dependency>
    </dependencies>

</project>

application.yaml

cosid:
  namespace: ${spring.application.name}
  snowflake:
    enabled: true
    #    epoch: 1577203200000
    clock-backwards:
      spin-threshold: 10
      broken-threshold: 2000
    machine:
      #      stable: true
      #      machine-bit: 10
      #      instance-id: ${HOSTNAME}
      distributor:
        type: redis
      #        manual:
      #          machine-id: 0
      state-storage:
        local:
          state-location: ./cosid-machine-state/
    share:
      clock-sync: true
      friendly: true
    provider:
      bizA:
        #        timestamp-bit:
        sequence-bit: 12
      bizB:
        #        timestamp-bit:
        sequence-bit: 12
  segment:
    enabled: true
    mode: chain
    chain:
      safe-distance: 100
      prefetch-period: 4000ns
    distributor:
      type: redis
    share:
      offset: 0
      step: 100
    provider:
      bizC:
        offset: 10000
        step: 100
      bizD:
        offset: 10000
        step: 100

JMH-Benchmark

  • 基準測試運行環境:筆記型電腦開發機 ( MacBook Pro (M1) )
  • 所有基準測試都在開發筆記型電腦上執行。
  • Redis 部署環境也在該筆記型電腦開發機上。

SnowflakeId

gradle cosid-core:jmh
# or
java -jar cosid-core/build/libs/cosid-core-1.1.8-jmh.jar -bm thrpt -wi 1 -rf json -f 1
Benchmark                                                    Mode  Cnt        Score   Error  Units
SnowflakeIdBenchmark.millisecondSnowflakeId_friendlyId      thrpt       4020311.665          ops/s
SnowflakeIdBenchmark.millisecondSnowflakeId_generate        thrpt       4095403.859          ops/s
SnowflakeIdBenchmark.safeJsMillisecondSnowflakeId_generate  thrpt        511654.048          ops/s
SnowflakeIdBenchmark.safeJsSecondSnowflakeId_generate       thrpt        539818.563          ops/s
SnowflakeIdBenchmark.secondSnowflakeId_generate             thrpt       4206843.941          ops/s

RedisIdBenchmark

RedisIdBenchmark

gradle cosid-redis:jmh
# or
java -jar cosid-redis/build/libs/cosid-redis-1.1.8-jmh.jar -bm thrpt -wi 1 -rf json -f 1 RedisIdBenchmark
Benchmark                    Mode  Cnt         Score         Error  Units
RedisIdBenchmark.step_1     thrpt    5    207470.850 ±   11832.936  ops/s
RedisIdBenchmark.step_100   thrpt    5   3868126.197 ±  258008.896  ops/s
RedisIdBenchmark.step_1000  thrpt    5  29506073.112 ± 2502253.182  ops/s

RedisChainIdBenchmark

RedisChainIdBenchmark

gradle cosid-redis:jmh
# or
java -jar cosid-redis/build/libs/cosid-redis-1.1.8-jmh.jar -bm thrpt -wi 1 -rf json -f 1 RedisChainIdBenchmark
Benchmark                                   Mode  Cnt          Score         Error  Units
RedisChainIdBenchmark.atomicLong_baseline  thrpt    5  143740421.831 ± 1142477.957  ops/s
RedisChainIdBenchmark.step_1               thrpt    5     301874.926 ±   10340.941  ops/s
RedisChainIdBenchmark.step_100             thrpt    5   25746336.165 ±  433565.840  ops/s
RedisChainIdBenchmark.step_1000            thrpt    5  102722840.616 ± 2368562.637  ops/s

RedisIdBenchmark VS RedisChainIdBenchmark TPS (ops/s)

Segemnt_Step1000_VS_throughput

RedisIdBenchmark VS RedisChainIdBenchmark Sample (us/op)

Segemnt_Step1000_VS_sample

java -jar cosid-redis/build/libs/cosid-redis-1.1.8-jmh.jar -bm sample -wi 1 -rf json -f 1 -tu us step_1000
Benchmark                                            Mode      Cnt    Score   Error  Units
RedisChainIdBenchmark.step_1000                    sample  1062954    0.056 ± 0.002  us/op
RedisChainIdBenchmark.step_1000:step_1000·p0.00    sample               ≈ 0          us/op
RedisChainIdBenchmark.step_1000:step_1000·p0.50    sample             0.042          us/op
RedisChainIdBenchmark.step_1000:step_1000·p0.90    sample             0.083          us/op
RedisChainIdBenchmark.step_1000:step_1000·p0.95    sample             0.084          us/op
RedisChainIdBenchmark.step_1000:step_1000·p0.99    sample             0.125          us/op
RedisChainIdBenchmark.step_1000:step_1000·p0.999   sample             3.000          us/op
RedisChainIdBenchmark.step_1000:step_1000·p0.9999  sample             8.818          us/op
RedisChainIdBenchmark.step_1000:step_1000·p1.00    sample           290.304          us/op
RedisIdBenchmark.step_1000                         sample  1374946    0.064 ± 0.003  us/op
RedisIdBenchmark.step_1000:step_1000·p0.00         sample               ≈ 0          us/op
RedisIdBenchmark.step_1000:step_1000·p0.50         sample             0.042          us/op
RedisIdBenchmark.step_1000:step_1000·p0.90         sample             0.042          us/op
RedisIdBenchmark.step_1000:step_1000·p0.95         sample             0.042          us/op
RedisIdBenchmark.step_1000:step_1000·p0.99         sample             0.083          us/op
RedisIdBenchmark.step_1000:step_1000·p0.999        sample             0.291          us/op
RedisIdBenchmark.step_1000:step_1000·p0.9999       sample            46.624          us/op
RedisIdBenchmark.step_1000:step_1000·p1.00         sample           483.840          us/op