如何清除与redis中某个字符串域关联的所有哈希?
How to clear all hashes associated with a certain string domain in redis?
例如我有User:1
、User:2
、User:3
...User:2000
。我想删除所有 User
以便重新开始。有没有一种方法可以在不知道确切密钥的情况下执行此操作,只是我想删除 User
域中的所有密钥?我有兴趣将此作为应用程序服务器启动任务的一部分。
比使用 'keys' 扫描所有键并通过正则表达式匹配删除更好的方法是使用标记机制,在服务器中维护一个 Redis SET 保存关系 Tag-Keys ,就像这个 post 上的那个:http://stackify.com/implementing-cache-tagging-redis/
我正在使用类似的方法,这是我最终用来设置与一个或多个标签相关的键值的 Lua 脚本:
local tagcount = 0
local cacheKey = KEYS[1]
local exp = ARGV[2]
local setValue = ARGV[1]
-- For each Tag, add the reference to the TagKey Set
for i=2,#KEYS do
local tag = ':tag:' .. KEYS[i]
local tagTtl = redis.call('ttl', tag)
tagcount = tagcount + redis.call('sadd', tag, cacheKey)
if(exp ~= nil and tagTtl ~= -1) then
-- Tag is volatile or was not found. Expiration provided. Set the Expiration.
redis.call('expire', tag, math.max(tagTtl, exp))
else
-- Tag is not volatile or the key to add is not volatile, mark the tag SET as not volatile
redis.call('persist', tag)
end
end
-- Set the cache key-value
if(setValue) then
if(exp ~= nil) then
redis.call('setex', cacheKey, exp, setValue)
else
redis.call('set', cacheKey, setValue)
end
end
return tagcount
请注意代表标签 SET 的键前面的“:tag:”。
如果您不需要通过标记删除键的原子方式,您可以使用 Redis 客户端在两个操作中完成,例如通过使用 [= 获取标记 "user" 的成员11=] 并使用 DEL key1 key2 ..
命令删除密钥。
例如我有User:1
、User:2
、User:3
...User:2000
。我想删除所有 User
以便重新开始。有没有一种方法可以在不知道确切密钥的情况下执行此操作,只是我想删除 User
域中的所有密钥?我有兴趣将此作为应用程序服务器启动任务的一部分。
比使用 'keys' 扫描所有键并通过正则表达式匹配删除更好的方法是使用标记机制,在服务器中维护一个 Redis SET 保存关系 Tag-Keys ,就像这个 post 上的那个:http://stackify.com/implementing-cache-tagging-redis/
我正在使用类似的方法,这是我最终用来设置与一个或多个标签相关的键值的 Lua 脚本:
local tagcount = 0
local cacheKey = KEYS[1]
local exp = ARGV[2]
local setValue = ARGV[1]
-- For each Tag, add the reference to the TagKey Set
for i=2,#KEYS do
local tag = ':tag:' .. KEYS[i]
local tagTtl = redis.call('ttl', tag)
tagcount = tagcount + redis.call('sadd', tag, cacheKey)
if(exp ~= nil and tagTtl ~= -1) then
-- Tag is volatile or was not found. Expiration provided. Set the Expiration.
redis.call('expire', tag, math.max(tagTtl, exp))
else
-- Tag is not volatile or the key to add is not volatile, mark the tag SET as not volatile
redis.call('persist', tag)
end
end
-- Set the cache key-value
if(setValue) then
if(exp ~= nil) then
redis.call('setex', cacheKey, exp, setValue)
else
redis.call('set', cacheKey, setValue)
end
end
return tagcount
请注意代表标签 SET 的键前面的“:tag:”。
如果您不需要通过标记删除键的原子方式,您可以使用 Redis 客户端在两个操作中完成,例如通过使用 [= 获取标记 "user" 的成员11=] 并使用 DEL key1 key2 ..
命令删除密钥。