扫描key

/**
     * @param key
     * @return
     * @Description: 通过Scan的方式迭代key
     */
    public Set<String> scanKeys(String key) {
        if (key == null) {
            return null;
        }
        return redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Set<String> keys = new HashSet<>();
            Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(key).build());
            while (cursor.hasNext()) {
                keys.add(new String(cursor.next()));
            }
            return keys;
        });
    }

扫描并删除

/**
     * @param key
     * @return
     * @Description: 通过Scan的方式迭代key并删除
     */
    public Long scanAndDeleteKeys(String key) {
        if (key == null) {
            return null;
        }
        return redisTemplate.execute((RedisCallback<Long>) connection -> {
            List<byte[]> keys = new ArrayList<>();
            Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(key).build());
            while (cursor.hasNext()) {
                keys.add(cursor.next());
            }
            return connection.del(keys.toArray(new byte[keys.size()][]));
        });
    }