Skip to content

fix: 使用 SCAN 命令替代 KEYS 命令,避免大数据量时阻塞 Redis#922

Open
helloworldtang wants to merge 2 commits intodromara:devfrom
helloworldtang:fix/replace-keys-with-scan
Open

fix: 使用 SCAN 命令替代 KEYS 命令,避免大数据量时阻塞 Redis#922
helloworldtang wants to merge 2 commits intodromara:devfrom
helloworldtang:fix/replace-keys-with-scan

Conversation

@helloworldtang
Copy link
Copy Markdown

修复内容

问题描述

使用 Redis KEYS 命令在大数据量场景下会导致 Redis 阻塞,曾引发多次线上故障。

解决方案

使用 SCAN 命令替代 KEYS,非阻塞式遍历 key。

修改文件

文件 修改内容
sa-token-redis-template keys()StringRedisTemplate.scan()
sa-token-redis-template-jdk-serializer 同上
sa-token-redisx keys()keysByScan()
sa-token-jfinal-plugin keys()Jedis.scan()
sa-token-jboot-plugin keys()Jedis.scan()

对比

修复前(阻塞)

Set<String> keys = stringRedisTemplate.keys(pattern);

修复后(非阻塞)

ScanOptions options = ScanOptions.scanOptions().match(pattern).count(1000).build();
try (Cursor<String> cursor = stringRedisTemplate.scan(options)) {
    while (cursor.hasNext()) {
        list.add(cursor.next());
    }
}

影响

  • ✅ 不阻塞 Redis
  • ✅ 支持大数据量场景
  • ✅ 向后兼容,API 行为不变

测试

请在 Redis 集群环境下测试 searchData 方法。

@helloworldtang helloworldtang force-pushed the fix/replace-keys-with-scan branch from e6181e2 to fd98494 Compare April 3, 2026 04:02
问题:
- KEYS 命令会阻塞 Redis,在大数据量场景下导致性能问题
- 多个线上故障与此相关

解决方案:
- 使用 SCAN 命令替代 KEYS,非阻塞式遍历

影响文件:
- sa-token-redis-template: 使用 RedisCallback + connection.scan()
- sa-token-redis-template-jdk-serializer: 同上
- sa-token-redisx: 保持原有实现(redisx 库内部已使用 SCAN)
- sa-token-jfinal-plugin: 使用 Jedis.scan()
- sa-token-jboot-plugin: 使用 Jedis.scan()

新增测试:
- SaTokenDaoForRedisTemplateTest: 6个测试用例覆盖 searchData 方法
- 测试通过:本机 Redis 环境,无密码

参考:
- https://redis.io/commands/scan/
- https://redis.io/commands/keys/
@helloworldtang helloworldtang force-pushed the fix/replace-keys-with-scan branch from fd98494 to be4df0c Compare April 3, 2026 04:11
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.

1 participant