Redis 批量删除 key
Redis Spring Boot Lua About 879 words需求背景
Spring Boot使用RedisTemplate时会把key存入\xac\xed\x00\x05w\x03这种格式,原因是因为RedisTemplate默认使用JdkSerializationRedisSerializer。可使用StringRedisTemplate代替之。
需批量删除\xac\xed\x00\x05w\x03开头的key。
解决方法
方法一
redis-cli -h 127.0.0.1 -p 6379 keys "*keys*" | xargs redis-cli -h 127.0.0.1 -p 6379 del
因为key是JDK序列化后的字符串,xargs读取出来是乱码,无法删除。故使用了方法二(适用于key不多的情况下)
xargs: Warning: a NUL character occurred in the input. It cannot be passed through in the argument list. Did you mean to use the --null option?
方法二
编写Lua文件,命名为del.lua:
local key=KEYS[1]
local list=redis.call("keys", key);
for i,v in ipairs(list) do
redis.call("del", v);
end
Redis调用Lua脚本,注意:这里的*keys*可替换为需要删除的关键字,如:*mykey*。
redis-cli -h 127.0.0.1 -p 6379 --eval ./del.lua "*keys*"
备注
如果批量删除的不是JDK序列化后的key,而key又很多的情况下,可使用scan扫描删除:
redis-cli -h 127.0.0.1 -p 6379 --scan --pattern '*keys*' | xargs -L 100 redis-cli -h 127.0.0.1 -p 6379 del
Views: 5,795 · Posted: 2019-10-21
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...