Redis刪除大Key

原文鏈接:https://www.dubby.cn/detail.html?id=9112

這里說的大key是指包含很多元素的set,sorted set,list和hash。

刪除操作,我們一般想到有2種,delexpire

DEL

Time complexity: O(N) where N is the number of keys that will be removed. When a key to remove holds a value other than a string, the individual complexity for this key is O(M) where M is the number of elements in the list, set, sorted set or hash. Removing a single key that holds a string value is O(1).

如果要刪除的key是一個集合,包含了很多元素,那么DEL時的耗時和元素個數(shù)成正比,所以如果直接DEL,會很慢。

EXPIRE

Note that calling EXPIRE/PEXPIRE with a non-positive timeout or EXPIREAT/PEXPIREAT with a time in the past will result in the key being deleted rather than expired (accordingly, the emitted key event will be del, not expired).

想著expire會不會可以不是直接刪除,可惜官網(wǎng)的描述讓我心灰意冷,如果expire后指定的timeout不是正數(shù),也就是<=0,那其實就是DEL

一點一點刪

我們知道Redis的工作線程是單線程的,如果一個command堵塞了,那所有請求都會超時,這時候,一些騷操作也許可以幫助你。

其實如果想刪除key,可以分解成2個目的,1:不想讓其他人訪問到這個key,2:釋放空間。

那其實我們可以分解成兩步,先用RENAME把原先的key rename成另一個key,比如:

RENAME userInfo:123 "deleteKey:userInfo:123"

然后可以慢慢去刪"deleteKey:userInfo:123",如果是set,那么可以用SREM慢慢刪,最后再用DEL徹底刪掉。

這里可以搞個task去SCAN deleteKey:*,然后慢慢刪除。

UNLINK

Redis 4.0.0提供了一個更加方便的命令

Available since 4.0.0.

Time complexity: O(1) for each key removed regardless of its size. Then the command does O(N) work in a different thread in order to reclaim memory, where N is the number of allocations the deleted objects where composed of.

UNLINK其實是直接返回,然后在后臺線程慢慢刪除。

如果你的Redis版本>=4.0.0,那么強烈建議使用UNLINK來刪除。

刪除耗時測試結(jié)果

單位:微秒

Set個數(shù) DEL EXPIRE UNLINK
1 90 97 75
10 79 67 100
100 51 49 47
1000 303 296 49
10000 2773 2592 52
100000 31210 33157 51
1000000 549388 501536 62
package main

import (
    "github.com/go-redis/redis"
    "fmt"
    "time"
)

func main() {
    client := redis.NewClient(&redis.Options{
        Addr:         "localhost:6379",
        Password:     "",
        DB:           0,
        ReadTimeout:  1000 * 1000 * 1000 * 60 * 60 * 24,
        WriteTimeout: 1000 * 1000 * 1000 * 60 * 60 * 24,
    })

    maxLength := int64(10000 * 100)

    for n := int64(1); n <= maxLength; n *= 10 {
        fmt.Println("Set個數(shù)", n)
        TestDelBigSet(client, n)
        TestExpireBigSet(client, n)
        TestUnlinkBigSet(client, n)
        fmt.Println()
    }
}

func TestDelBigSet(client *redis.Client, count int64) {
    redisKey := fmt.Sprintf("%s%d", "del:", time.Now().Nanosecond())

    for n := int64(0); n < count; n++ {
        err := client.SAdd(redisKey, fmt.Sprintf("%d", n)).Err()
        if err != nil {
            panic(err)
        }
    }

    startTime := CurrentTimestampInMicroSecond()
    client.Del(redisKey)
    endTime := CurrentTimestampInMicroSecond()

    fmt.Println("Del", endTime-startTime)
}

func TestUnlinkBigSet(client *redis.Client, count int64) {
    redisKey := fmt.Sprintf("%s%d", "unlink:", time.Now().Nanosecond())

    for n := int64(0); n < count; n++ {
        err := client.SAdd(redisKey, fmt.Sprintf("%d", n)).Err()
        if err != nil {
            panic(err)
        }
    }
    startTime := CurrentTimestampInMicroSecond()
    client.Unlink(redisKey)
    endTime := CurrentTimestampInMicroSecond()

    fmt.Println("Unlink", endTime-startTime)
}

func TestExpireBigSet(client *redis.Client, count int64) {
    redisKey := fmt.Sprintf("%s%d", "expire:", time.Now().Nanosecond())

    for n := int64(0); n < count; n++ {
        err := client.SAdd(redisKey, fmt.Sprintf("%d", n)).Err()
        if err != nil {
            panic(err)
        }
    }
    startTime := CurrentTimestampInMicroSecond()
    client.Expire(redisKey, 0)
    endTime := CurrentTimestampInMicroSecond()

    fmt.Println("Expire", endTime-startTime)
}

func CurrentTimestampInMicroSecond() int64 {
    return time.Now().UnixNano() / 1000
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,224評論 6 529
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 97,916評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,014評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,466評論 1 308
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,245評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,795評論 1 320
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,869評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,010評論 0 285
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,524評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,487評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,634評論 1 366
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,173評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 43,884評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,282評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,541評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,236評論 3 388
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,623評論 2 370

推薦閱讀更多精彩內(nèi)容