在我的Redis DB中,我有一些前缀:<numeric_id>哈希值。

有时我想把它们都原子地清除掉。如何在不使用分布式锁定机制的情况下做到这一点呢?


当前回答

FYI.

只使用bash和redis-cli 不使用键(这使用扫描) 在集群模式下工作良好 不是原子

也许您只需要修改大写字符。

scan-match.sh

#!/bin/bash
rcli="/YOUR_PATH/redis-cli" 
default_server="YOUR_SERVER"
default_port="YOUR_PORT"
servers=`$rcli -h $default_server -p $default_port cluster nodes | grep master | awk '{print $2}' | sed 's/:.*//'`
if [ x"$1" == "x" ]; then 
    startswith="DEFAULT_PATTERN"
else
    startswith="$1"
fi
MAX_BUFFER_SIZE=1000
for server in $servers; do 
    cursor=0
    while 
        r=`$rcli -h $server -p $default_port scan $cursor match "$startswith*" count $MAX_BUFFER_SIZE `
        cursor=`echo $r | cut -f 1 -d' '`
        nf=`echo $r | awk '{print NF}'`
        if [ $nf -gt 1 ]; then
            for x in `echo $r | cut -f 1 -d' ' --complement`; do 
                echo $x
            done
        fi
        (( cursor != 0 ))
    do
        :
    done
done

clear-redis-key.sh

#!/bin/bash
STARTSWITH="$1"

RCLI=YOUR_PATH/redis-cli
HOST=YOUR_HOST
PORT=6379
RCMD="$RCLI -h $HOST -p $PORT -c "

./scan-match.sh $STARTSWITH | while read -r KEY ; do
    $RCMD del $KEY 
done

在bash提示符下运行

$ ./clear-redis-key.sh key_head_pattern

其他回答

我用EVAL命令的最简单的变体继承了这一点:

EVAL "return redis.call('del', unpack(redis.call('keys', 'my_pattern_here*')))" 0

我用我的值替换了my_pattern_here。

@itamar的回答很棒,但对回复的解析对我来说并不管用,特别是在给定扫描中没有找到键的情况下。一个可能更简单的解决方案,直接从控制台:

redis-cli -h HOST -p PORT  --scan --pattern "prefix:*" | xargs -n 100 redis-cli DEL

这也使用了SCAN,它在生产中比KEYS更可取,但不是原子的。

在bash执行:

redis-cli KEYS "prefix:*" | xargs redis-cli DEL

更新

好的,我明白了。这种方式怎么样:存储当前额外的增量前缀,并将其添加到所有的键。例如:

你的价值观是这样的:

prefix_prefix_actuall = 2
prefix:2:1 = 4
prefix:2:2 = 10

当您需要清除数据时,首先更改prefix_actuall(例如set prefix_prefix_actuall = 3),因此您的应用程序将把新数据写入关键字prefix:3:1和prefix:3:2。然后,您可以安全地从prefix:2:1和prefix:2:2中获取旧值并清除旧键。

如果你使用windows环境,请遵循以下步骤,它一定会工作:

Download GOW from here - https://github.com/bmatzelle/gow/wiki (because xargs command doesn't works in windows) Download redis-cli for Windows (detailed explanation is here - https://medium.com/@binary10111010/redis-cli-installation-on-windows-684fb6b6ac6b) Run cmd and open directory where redis-cli stores (example: D:\Redis\Redis-x64-3.2.100) if you want to delete all keys which start with "Global:ProviderInfo" execute this query (it's require to change bold parameters (host, port, password, key) and write yours, because of this is only example): redis-cli -h redis.test.com -p 6379 -a redispassword --raw keys "Global:ProviderInfo*" | xargs redis-cli -h redis.test.com -p 6379 -a redispassword del

Spring RedisTemplate本身提供了这个功能。RedissonClient在最新版本中已经弃用了“deletebyppattern”功能。

Set<String> keys = redisTemplate.keys("geotag|*");
redisTemplate.delete(keys);