redis模糊删除

  /**
     * 模糊匹配前缀key  如: storageRent:*
     *
     * 由于keys被禁了  也不提倡使用,于是用了scan 去模糊匹配 类似分页查询  数据量大也不怕
     *
     * @patternKey 需要模糊匹配的前缀
     */
    @Override
    public void deleteKeys(String patternKey) {

        redisTemplate.execute((RedisCallback>) connection -> {

            Set binaryKeys = new HashSet<>();
            Cursor cursor = connection.scan(ScanOptions.scanOptions().count(1000).match(patternKey+"*").build());

            try {
                while (cursor.hasNext()) {
                    binaryKeys.add(new String(cursor.next(), StandardCharsets.UTF_8));
                }
                log.info(binaryKeys.toString());
                redisTemplate.delete(binaryKeys);
            } finally {
                try {
                    cursor.close();
                } catch (IOException e) {
                    log.error("redis 异常",e);
                }
            }

            return binaryKeys;
        });
    }

 

你可能感兴趣的:(redis模糊删除)