基于悲观锁与独立计数表的分布式无间隙序列号生成方案

本文探讨了在多应用实例环境下生成无间隙序列号的挑战与解决方案。针对传统方法可能导致间隙的问题,提出了一种基于独立计数表和数据库悲观写锁的策略。该方案通过将序列号的生成和更新操作封装在单个数据库事务中,并利用悲观锁确保并发访问的原子性和隔离性,从而有效避免了序列号的间隙,即使在分布式高并发场景下也能保持数据的完整性和连续性。

在构建分布式系统时,为设备或记录生成唯一且无间隙的序列号是一项常见的需求。例如,一个设备编号可能由“系列前缀”和“递增数字”组成(如AA-001, AA-002),当某一“系列”的数字达到上限后,自动切换到下一个“系列”并重新从1开始编号。关键挑战在于,多个应用实例同时请求序列号时,如何确保数字的连续性,即不能出现任何跳号(间隙),即使在数据库回滚的情况下也要避免。传统的通过查询最大值(findMax())然后递增的方法,在高并发和事务回滚的场景下,极易产生间隙或竞态条件。

解决方案:基于独立计数表与悲观锁的策略

为了解决多实例环境下无间隙序列号生成的问题,可以采用一种结合独立计数表和数据库悲观锁的策略。这种方法将序列号的维护与业务数据分离,并严格控制并发访问。

1. 独立计数表设计

首先,创建一个专门用于存储各系列当前序列号的独立表,例如命名为 series_counter。这张表只包含两个核心字段:

  • series_id:表示当前序列号所属的系列标识符。
  • current_counter:存储该系列下一个可用的序列号。

当一个新的系列被引入时,需要在此表中为该系列添加一条初始记录,例如 AA | 1。

CREATE TABLE series_counter (
    series_id VARCHAR(50) PRIMARY KEY,
    current_counter BIGINT NOT NULL DEFAULT 1
);

-- 示例数据
INSERT INTO series_counter (series_id, current_counter) VALUES ('AA', 1);
INSERT INTO series_counter (series_id, current_counter) VALUES ('BB', 1);
-- ...以此类推

2. 核心业务逻辑实现

序列号的生成和使用必须在一个原子操作中完成,这通常通过数据库事务和悲观锁来实现。核心流程包括:获取当前计数、使用该计数生成新记录、然后递增计数并保存。

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.LockModeType;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

// SeriesCounter 实体类示例
@Entity // 假设使用JPA
@Table(name = "series_counter")
class SeriesCounter {
    @Id
    private String seriesId; // 使用seriesId作为主键
    private Long currentCounter;

    // 构造函数、Getter、Setter (通常由Lombok @Data 或手动生成)
    public SeriesCounter() {}

    public SeriesCounter(String seriesId, Long currentCounter) {
        this.seriesId = seriesId;
        this.currentCounter = currentCounter;
    }

    public String getSeriesId() { return seriesId; }
    public void setSeriesId(String seriesId) { this.seriesId = seriesId; }
    public Long getCurrentCounter() { return currentCounter; }
    public void setCurrentCounter(Long currentCounter) { this.c

urrentCounter = currentCounter; } public void incrementValue() { this.currentCounter++; } } // SeriesCounterRepository 接口示例 public interface SeriesCounterRepo extends JpaRepository { @Lock(LockModeType.PESSIMISTIC_WRITE) // 施加悲观写锁 // @Transactional // 某些特殊情况下,JPA仓库方法也可能需要此注解,但通常由调用方服务层事务管理 @Query("SELECT sc FROM SeriesCounter sc WHERE sc.seriesId = :seriesId") SeriesCounter fetchLatest(@Param("seriesId") String seriesId); } // 业务逻辑服务类示例 @Service public class DeviceNumberGeneratorService { @Autowired private SeriesCounterRepo seriesCounterRepo; // @Autowired // private SeriesRepository seriesRepo; // 假设有一个用于保存设备记录的Repository @Transactional // 确保整个操作在单个事务中完成 public String generateDeviceNumber(String seriesId) { // 1. 获取并锁定当前系列的计数器 // 此时,其他尝试获取相同seriesId的请求将被阻塞,直到当前事务完成 SeriesCounter latestCounter = seriesCounterRepo.fetchLatest(seriesId); if (latestCounter == null) { // 处理系列不存在的情况,可能需要初始化或抛出异常 throw new IllegalArgumentException("Series not found: " + seriesId); } Long currentNumber = latestCounter.getCurrentCounter(); // 2. 构建新的设备编号(或设备记录) String newDeviceNumber = seriesId + "-" + String.format("%03d", currentNumber); // 示例格式化 // 假设这里是创建并保存实际的设备记录 // Series newSeriesRecord = new Series(seriesId, currentNumber, ...); // seriesRepo.save(newSeriesRecord); // 3. 递增计数器并保存 latestCounter.incrementValue(); seriesCounterRepo.save(latestCounter); // 更新计数器 // 4. 返回生成的设备编号 return newDeviceNumber; } }

3. 悲观锁机制详解

`@Lock(