11

通常,我获取密钥集,然后使用外观删除每个键/值对。

是否可以通过模式删除所有键?

IE:

Del sample_pattern:*
4

5 回答 5

21

对于 Jedis 来说,“按模式删除”似乎基本上是获取特定模式的所有键,然后循环遍历它。

IE

Set<String> keys = jedis.keys(pattern);
for (String key : keys) {
    jedis.del(key);
} 
于 2014-01-27T17:10:44.020 回答
17

KEYS 不建议使用,因为它在生产中使用时效率低下。请参阅https://redis.io/commands/keys。相反,最好使用 SCAN。此外,比重复调用 jedis.del() 更有效的调用是对 jedis 进行一次调用以删除匹配的键,并传入要删除的键数组。一个更有效的解决方案如下:

Set<String> matchingKeys = new HashSet<>();
ScanParams params = new ScanParams();
params.match("sample_pattern:*");

try(Jedis jedis = jedisPoolFactory.getPool().getResource()) {
    String nextCursor = "0";

    do {
        ScanResult<String> scanResult = jedis.scan(nextCursor, params);
        List<String> keys = scanResult.getResult();
        nextCursor = scanResult.getStringCursor();

        matchingKeys.addAll(keys);

    } while(!nextCursor.equals("0"));

    if (matchingKeys.size() == 0) {
      return;
    }

    jedis.del(matchingKeys.toArray(new String[matchingKeys.size()]));
}
于 2017-03-09T18:18:27.407 回答
5

您应该尝试使用eval。我不是 Lua 专家,但这段代码有效。

private static final String DELETE_SCRIPT_IN_LUA =
    "local keys = redis.call('keys', '%s')" +
    "  for i,k in ipairs(keys) do" +
    "    local res = redis.call('del', k)" +
    "  end";

public void deleteKeys(String pattern) {
  Jedis jedis = null;

  try {
    jedis = jedisPool.getResource();

    if (jedis == null) {
      throw new Exception("Unable to get jedis resource!");
    }

    jedis.eval(String.format(DELETE_SCRIPT_IN_LUA, pattern));  
  } catch (Exception exc) {
    if (exc instance of JedisConnectionException && jedis != null) {
      jedisPool.returnBrokenResource(jedis);
      jedis = null;
    }

    throw new RuntimeException("Unable to delete that pattern!");
  } finally {
    if (jedis != null) {
      jedisPool.returnResource(jedis);
    }
  }
}

然后调用:

deleteKeys("temp:keys:*");

这保证了一个服务器端调用,多个删除操作。

于 2014-05-03T12:01:12.233 回答
3

您可以在一行中使用Redisson完成此操作:

redisson.getKeys().deleteByPattern(pattern)
于 2015-11-29T16:49:02.390 回答
1

你可以用 bash 做到这一点:

$ redis-cli KEYS "sample_pattern:*" | xargs redis-cli DEL
于 2014-01-23T19:26:10.517 回答