鉴于我有存储在Redis中的KEY值,并希望以模式开始的键过期。
例如:
SET hello.world "Hello"
SET there.how "There"
SET hello.are.you "Are you"
然后在密钥设置之后,想要过期所有以&;hello&;开头的密钥。假设确实有大量的键,而不仅仅是这个简单的例子。不希望对Redis进行多次往返调用。
我认为最简单的方法就是用scan(pattern)
来迭代所有的键,用pipeline
来过期,它会做一定的往返,就像你说的
def while_true_loop():
target_pattern = 'hello.([A-Za-z0-9]*)$'
simple_pattern = 'hello.*'
import re
cursor = 0
while True:
cursor, keys = rs.scan(cursor, match=simple_pattern, count=1000)
pipe = rs.pipeline()
for key in keys:
if re.match(target_pattern, key):
pipe.expire(key, 3600)
pipe.execute()
if not keys:
break