日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

解決redis批量刪除key值的問題_Redis

作者:m0_67403240 ? 更新時(shí)間: 2022-05-26 編程語言

遇到的問題:

在開發(fā)過程中,會(huì)遇到要批量刪除某種規(guī)則的key,例如login_logID(ID為變量),現(xiàn)在需要?jiǎng)h除"login_log*"這一類的數(shù)據(jù),但是redis本身只有批量查詢一類key值的命令keys,但是沒有批量刪除某一個(gè)類的命令。

解決辦法:

先查詢,在刪除,使用xargs傳參(xargs可以將管道或標(biāo)準(zhǔn)輸入(stdin)數(shù)據(jù)轉(zhuǎn)換成命令行參數(shù)),先執(zhí)行查詢語句,在將查詢出來的key值,當(dāng)初del的參數(shù)去刪除。

redis-cli  KEYS key* (查找條件) | xargs redis-cli  del 

=>[執(zhí)行后返回的結(jié)果影響數(shù)量]:(integer) 10[數(shù)量10個(gè)]
做個(gè)實(shí)驗(yàn),先創(chuàng)三個(gè)同類型的key值

127.0.0.1:6379> set test1 1
OK
127.0.0.1:6379> set test2 2
OK
127.0.0.1:6379> set test3 3
OK

查詢keys

127.0.0.1:6379> keys test*
1) "test3"
2) "test2"
3) "test1"

退出redis,在本地執(zhí)行刪除命令

[root@localhost redis]# redis-cli -a 密碼 -n 0(數(shù)據(jù)庫) keys "test*" |xargs redis-cli -a 密碼 -n 0(數(shù)據(jù)庫)  del
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
(integer) 3 (返回行數(shù))

原理解析:

這個(gè)命令是先通過redis客戶端執(zhí)行了keys命令,模糊搜索出所有的key,通過xargs命令,將前面查詢出來的key作為后面redis的del命令的輸入
相當(dāng)于執(zhí)行了 redis-cli del test1 test2 test3

注意:這里執(zhí)行時(shí)需要帶上redis條件,-a是輸入密碼,-n是指定數(shù)據(jù)庫,如果redis不在本地或者其他有變動(dòng)還需要加上-h redis所在服務(wù)器ip,-p端口

例如

redis-cli -h 127.0.0.1(IP地址) -p 6379 (端口號(hào)) -a 密碼 -n 1(數(shù)據(jù)在第幾個(gè)庫就寫幾) KEYS key* (查找條件) | xargs redis-cli (-h (IP地址) -p 6379 (端口號(hào)) -a 密碼 -n 1 ) del

補(bǔ)充知識(shí):

redis中的刪除
1.Redis DEL 命令用于刪除已存在的鍵,不存在的 key 會(huì)被忽略。
例如:

127.0.0.1:6379> set hello world
OK
127.0.0.1:6379> del hello
(integer) 1

但是del只能刪除一個(gè)或多個(gè),不能批量刪除,當(dāng)需要?jiǎng)h除數(shù)據(jù)量過大時(shí)就不適用了
2.清空整個(gè) Redis 服務(wù)器的數(shù)據(jù):flushall
3.清空當(dāng)前庫中的所有 key:flushdb

原文鏈接:https://blog.csdn.net/m0_67403240/article/details/123680399

欄目分類
最近更新