配置文件

将想要禁止的命令,按以下格式加入配置文件中

rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command KEYS ""

在Spring Data Redis 中使用Scan代替 keys

注意: 版本要大于 1.6.0.RELEASE(不包括此版本!会有 NoSuchElements 的bugs)

public class RedisKeysPatternUtils {
    private RedisKeysPatternUtils() {
    }

    public static final Set<String> getKeys(final RedisOperations<String, ?> redisOperations, final String keysPattern) {
        Set<String> keys = redisOperations.execute(new RedisCallback<Set<String>>() {
            @Override
            public Set<String> doInRedis(RedisConnection connection) throws DataAccessException {
                Set<String> binaryKeys = new HashSet<>();
                Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(keysPattern).count(5000).build());
                while (cursor.hasNext()) {
                    byte[] key = cursor.next();
                    binaryKeys.add(new String(key, StandardCharsets.UTF_8));
                }
                try {
                    cursor.close();
                } catch (IOException e) {
                }

                return binaryKeys;
            }
        });
        return keys;
    }
}

后记

请千万千万不要用keys这种命令! 请千万千万不要用keys这种命令! 请千万千万不要用keys这种命令!

重要的事情,要说三次!