Class JdbcSegmentAllocator

java.lang.Object
cloud.opencode.base.id.segment.JdbcSegmentAllocator
All Implemented Interfaces:
SegmentAllocator

public final class JdbcSegmentAllocator extends Object implements SegmentAllocator
JDBC-based Segment Allocator 基于JDBC的号段分配器

Allocates ID segments from a database table. Uses optimistic locking for concurrent safety.

从数据库表分配ID号段。使用乐观锁确保并发安全。

Table Schema | 表结构:

CREATE TABLE id_segment (
    biz_tag VARCHAR(128) NOT NULL PRIMARY KEY,
    max_id BIGINT NOT NULL DEFAULT 0,
    step INT NOT NULL DEFAULT 1000,
    version INT NOT NULL DEFAULT 0,
    update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Features | 主要功能:

  • Optimistic locking - 乐观锁
  • Auto table creation - 自动建表
  • Configurable step size - 可配置步长

Usage Examples | 使用示例:

DataSource dataSource = ...;
JdbcSegmentAllocator allocator = JdbcSegmentAllocator.create(
    dataSource,
    "id_segment",
    1000
);

// Initialize table (first time only)
allocator.initTable();

// Allocate segment
Segment segment = allocator.allocate("order");

Security | 安全性:

  • Thread-safe: Yes - 线程安全: 是
Since:
JDK 25, opencode-base-id V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • create

      public static JdbcSegmentAllocator create(DataSource dataSource)
      Creates an allocator with default settings 使用默认设置创建分配器
      Parameters:
      dataSource - the data source | 数据源
      Returns:
      allocator | 分配器
    • create

      public static JdbcSegmentAllocator create(DataSource dataSource, String tableName, int step)
      Creates an allocator with custom settings 使用自定义设置创建分配器
      Parameters:
      dataSource - the data source | 数据源
      tableName - the table name | 表名
      step - the step size | 步长
      Returns:
      allocator | 分配器
    • allocate

      public SegmentAllocator.Segment allocate(String bizTag)
      Description copied from interface: SegmentAllocator
      Allocates a segment for the given business tag 为给定业务标识分配号段
      Specified by:
      allocate in interface SegmentAllocator
      Parameters:
      bizTag - the business tag | 业务标识
      Returns:
      allocated segment | 分配的号段
    • getStep

      public int getStep()
      Description copied from interface: SegmentAllocator
      Gets the step size 获取步长
      Specified by:
      getStep in interface SegmentAllocator
      Returns:
      step size | 步长
    • initTable

      public void initTable()
      Initializes the table structure 初始化表结构