redis模糊匹配用keys还是scan
前言
实际业务开发中可能有遇到根据表达式去redis批量获取key, 例如 keys pattern, 但实际reids keys * 是线程阻塞的,如果数据量较大可能导致业务中断使用,严重甚至导致redis服务崩溃,我们应使用scan命令来查找,具体语法为*
SCAN cursor [MATCH pattern] [COUNT count]
- cursor - 游标。
- pattern - 匹配的模式。
- count - 指定从数据集里返回多少元素,默认值为 10
Java使用scan
RedisTemplate
代码如下(示例):
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class RedisUtils {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public Set<String> scanPattern(String pattern) {
int scanCount = 1000;
return (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
final Set<String> resultSet = Sets.newLinkedHashSet();
try {
final MultiKeyCommands multiKeyCommands = (MultiKeyCommands) connection.getN