Redis/Jedis - Delete by pattern?

前端 未结 5 591
渐次进展
渐次进展 2021-02-04 11:38

Normally, I get the key set then use a look to delete each key/value pair.

Is it possible to just delete all keys via pattern?

ie:

Del sample_pat         


        
5条回答
  •  清酒与你
    2021-02-04 12:14

    You should try using eval. I'm no Lua expert, but this code works.

    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);
        }
      }
    }
    

    And then call:

    deleteKeys("temp:keys:*");
    

    This guarantees a one server-side call, multiple delete operation.

提交回复
热议问题