Skip to content

Comments

feat(idgen): 为 Sequencer 添加 Set 和 SetIfNotExists 方法#28

Merged
ceyewan merged 1 commit intomainfrom
feat/idgen-set-methods
Jan 3, 2026
Merged

feat(idgen): 为 Sequencer 添加 Set 和 SetIfNotExists 方法#28
ceyewan merged 1 commit intomainfrom
feat/idgen-set-methods

Conversation

@ceyewan
Copy link
Owner

@ceyewan ceyewan commented Jan 3, 2026

概述

idgen.Sequencer 接口添加 SetSetIfNotExists 方法,解决 issue #27 中描述的序列号初始化需求。

变更内容

接口变更 (idgen.go)

type Sequencer interface {
    Next(ctx context.Context, key string) (int64, error)
    NextBatch(ctx context.Context, key string, count int) ([]int64, error)
    
    // 新增:
    Set(ctx context.Context, key string, value int64) error
    SetIfNotExists(ctx context.Context, key string, value int64) (bool, error)
}

实现细节 (sequence.go)

  • Set: 直接设置序列号值,使用 Redis SET 命令,会覆盖现有值
  • SetIfNotExists: 仅当键不存在时设置,使用 Redis SETNX 命令,返回 bool 表示是否设置成功
  • 两个方法均对负值进行校验,返回 ErrInvalidInput 错误
  • 完整的日志记录(Debug 和 Error 级别)

测试覆盖 (idgen_test.go)

  • TestSequencer_Set: 基本设置、负值校验、覆盖行为、前缀处理
  • TestSequencer_SetIfNotExists: 新键设置、已存在键处理、负值校验、IM 场景模拟

使用场景

IM 系统中会话消息序列号初始化:

// 安全初始化:仅在首次部署时设置起始值
ok, err := sequencer.SetIfNotExists(ctx, "conversation:123", 100)
if err != nil { /* 处理错误 */ }
if !ok {
    // 键已存在,可能是其他进程已初始化
}

// 后续正常递增
seq, _ := sequencer.Next(ctx, "conversation:123") // 101

测试

所有测试通过:

go test -v ./idgen/
PASS
ok  	github.com/ceyewan/genesis/idgen	0.434s

Closes #27

🤖 Generated with Claude Code

- 在 Sequencer 接口添加 Set 和 SetIfNotExists 方法
- Set: 直接设置序列号的值,覆盖现有值
- SetIfNotExists: 仅当键不存在时设置,返回 bool 表示是否设置成功
- 两个方法均对负值进行校验
- 添加完整的单元测试,包括 IM 场景的初始化测试
- 解决 issue #27 中描述的序列号初始化需求

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@ceyewan ceyewan merged commit 7ad90f6 into main Jan 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] 为 Sequencer 添加 Set/SetIfNotExists 方法

1 participant