redis應該如何刪除集合

 背景

在redis的命令接口中,沒有專門針對list,set,hash等數據結構的key刪除命令,只有指定到刪除具體的對象的操作命令。
比如刪除list列表的元素命令LREM,刪除set集合中一個或多個元素命令SREM,刪除hash中一個或多個元素HDEL。
而在redis的一些使用中還是可能遇到對這些集合類對象整體刪除的場景如:
場景1:當用戶的信息使用hash結構儲存時,需要刪除整個用戶的信息
場景2:刪除大V的粉絲列表

DEL

在redis4.0之前可以用del命令直接刪除key,但是由於redis是單線程,如果對應value值很多,就會出現嚴重的阻塞問題。
官網給出了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).

大概意思是:當有N個keys 要被移除時,時間複雜度是O(N);當要移除的key對應的value不是string,這是移除單個key的時間複雜度是O(M),這裏的M是list,set,有序set或hash數據結構裏面的元素。移除單個key,並且這個key對應的value是一個string類型,這時的時間複雜度是O(1).

因此,在list,set,有序set或hash數據結構裏面的元素較少時,可以使用del刪除對應的key。

 

UNLINK

爲了解決刪除大key的問題, Redis 4.0 新添加了 UNLINK 命令用於執行大KEY異步刪除。

官網給出unlink時間複雜度:

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來刪除。


參考:https://blog.csdn.net/u011499747/article/details/83055864 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章