php redis hash删除key,如何优雅的删除Redis的大key

关于Redis大键(Key),我们从[空间复杂性]和访问它的[时间复杂度]两个方面来定义大键。前者主要表示Redis键的占用内存大小;后者表示Redis集合数据类型(set/hash/list/sorted set)键,所含有的元素个数。以下两个示例:

1个大小200MB的String键(String Object最大512MB),内存空间占用较大;1个包含100000000(1kw)个字段的Hash键,对应访问模式(如hgetall)时间复杂度高

因为内存空间复杂性处理耗时都非常小,测试 del 200MB String键耗时约1毫秒,而删除一个含有1kw个字段的Hash键,却会阻塞Redis进程数十秒。所以本文只从时间复杂度分析大的集合类键。删除这种大键的风险,以及怎么优雅地删除。

在Redis集群中,应用程序尽量避免使用大键;直接影响容易导致集群的容量和请求出现”倾斜问题“,具体分析见文章:redis-cluster-imbalance。但在实际生产过程中,总会有业务使用不合理,出现这类大键;当DBA发现后推进业务优化改造,然后删除这个大键;如果直接删除它,DEL命令可能阻塞Redis进程数十秒,对应用程序和Redis集群可用性造成严重的影响。

一、直接删除大Key的风险

DEL命令在删除单个集合类型的Key时,命令的时间复杂度是O(M),其中M是集合类型Key包含的元素个数。

DEL keyTime 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,导致Redis阻塞,出现故障切换和应用程序雪崩的故障。测试删除集合类型大Key耗时,一般每秒可清理100w~数百w个元素; 如果数千w个元素的大Key时,会导致Redis阻塞上10秒可能导致集群判断Redis已经故障,出现故障切换;或应用程序出现雪崩的情况。

说明:Redis是单线程处理。单个耗时过大命令,导致阻塞其他命令,容易引起应用程序雪崩或Redis集群发生故障切换。所以避免在生产环境中使用耗时过大命令。

Redis删除大的集合键的耗时, 测试估算,可参考;和硬件环境、Redis版本和负载等因素有关

Key类型

Item数量

耗时

Hash

~100万

~1000ms

List

~100万

~1000ms

Set

~100万

~1000ms

Sorted Set

~100万

~1000ms

当我们发现集群中有大key时,要删除时,如何优雅地删除大Key?

二、如何优雅地删除各类大Key

从Redis2.8版本开始支持SCAN命令,通过m次时间复杂度为O(1)的方式,遍历包含n个元素的大key.这样避免单个O(n)的大命令,导致Redis阻塞。 这里删除大key操作的思想也是如此。

2.1  Delete Large Hash Key

通过hscan命令,每次获取500个字段,再用hdel命令,每次删除1个字段。Python代码:

def del_large_hash():

r = redis.StrictRedis(host='redis-host1', port=6379)

large_hash_key ="xxx"

cursor = '0'

while cursor != 0:

cursor, data = r.hscan(large_hash_key, cursor=cursor, count=500)

for item in data.items():

r.hdel(large_hash_key, item[0])

2.2  Delete Large Set Key

删除大set键,使用sscan命令,每次扫描集合中500个元素,再用srem命令每次删除一个键Python代码:

def del_large_set():

r = redis.StrictRedis(host='redis-host1', port=6379)

large_set_key = 'xxx'

cursor = '0'

while cursor != 0:

cursor, data = r.sscan(large_set_key, cursor=cursor, count=500)

for item in data:

r.srem(large_size_key, item)

2.3  Delete Large List Key

删除大的List键,未使用scan命令; 通过ltrim命令每次删除少量元素。Python代码:

def del_large_list():

r = redis.StrictRedis(host='redis-host1', port=6379)

large_list_key = 'xxx'

while r.llen(large_list_key)>0:

r.ltrim(large_list_key, 0, -101)

2.4  Delete Large Sorted set key

删除大的有序集合键,和List类似,使用sortedset自带的zremrangebyrank命令,每次删除top 100个元素。Python代码:

def del_large_sortedset():

r = redis.StrictRedis(host='large_sortedset_key', port=6379)

large_sortedset_key='xxx'

while r.zcard(large_sortedset_key)>0:

r.zremrangebyrank(large_sortedset_key,0,99)

三、Redis Lazy Free

应该从3.4版本开始,Redis会支持lazy delete free的方式,删除大键的过程不会阻塞正常请求。