Redis:如何删除多个键匹配模式?

aoyhnmkz  于 2022-12-11  发布在  Redis
关注(0)|答案(5)|浏览(170)

我需要取出一万把钥匙。
1.何宁道:执行这种脚本
“返回redis.call为0“ROOT
1.可能更好的是设置到期时间,Redis将删除它们?但如何在控制台使用Lua脚本?
该脚本(见上文)之所以有效,是因为del comman das具有以下格式:

del key1 key2 ...

但是Expire只对1个密钥有效。
有可能用lua脚本实现吗?
例如:我的应用程序创建了一些搜索结果缓存,并为每个页面设置ttl = 3600。但用户希望立即清除缓存,即删除所有匹配的键或为它们设置更小的过期时间。

ql3eal8s

ql3eal8s1#

您可以使用(从redis cli)删除所有密钥:

flushall

或从命令行运行此命令(bash)

redis-cli --scan --pattern aihello_user* | xargs redis-cli del
khbbv19g

khbbv19g2#

如果你正在尝试删除匹配前缀的键,那么你可以尝试下面的命令

redis-cli keys <PREFIX>'*' | xargs redis-cli del

此处**keys '*'**将给予所有具有匹配前缀的键,然后del命令将删除所有键。

zkure5ic

zkure5ic3#

Whether you DEL or EXPIRE , once Lua script runs it will block other clients and if it runs for too long it the lua-time-limit timeout. Despite your reluctance for looping, I strongly recommend you do.
Expiry vs deletion may lessen some of the immediate load (yet to be empirically proven), so feel free to go with one or the other. In either case, use a client-side loop on a SCAN operation to invoke the command for each key. If you have a server/worker process somewhere in your architecture, you can consider delegating this task to it so the client will not be kept busy.
EDIT per comment: Variadic commands such as DEL are generally more performant than non-variadic commands, however here you're comparing two different operations so there are no assurances. The DEL approach is potentially more blocking because Redis will actually go ahead and delete the keys immediately - if you have a lot of keys to delete and/or their values are big, this could take more time. The EXPIRE approach tries to avoid this by leveraging on Redis' lazy expiry mechanism (it uses idle time to do so when possible), so the deletion-due-to-expiry load is theoretically better distributed. The best way to determine which works better for you is by testing both and comparing - I'd love to learn of your results!

8fsztsew

8fsztsew4#

我到处找这个,最后写了一个bash脚本,它包含一个主机、端口和一个模式。看起来工作得很好。下面是Gist

if [ $# -ne 3 ] 
then
  echo "Delete keys from Redis matching a pattern using SCAN & DEL"
  echo "Usage: $0 <host> <port> <pattern>"
  exit 1
fi

cursor=-1
keys=""

while [ $cursor -ne 0 ]; do
  if [ $cursor -eq -1 ]
  then
    cursor=0
  fi

  reply=`redis-cli -h $1 -p $2 SCAN $cursor MATCH $3`
  cursor=`expr "$reply" : '\([0-9]*[0-9 ]\)'`
  if [[ $reply = *[[:space:]]* ]]
  then
    keys=${reply#[0-9]*[[:space:]]}
    for key in $keys; do
      echo "Delete the following key: $key"
      redis-cli -h $1 -p $2 DEL $key 
    done
  fi
done
mutmk8jj

mutmk8jj5#

redis-cli -h 127.0.0.1 -p 6379 --scan --pattern <pattern>* | xargs redis-cli unlink

使用扫描和取消链接不是阻止功能

相关问题