redis - 如何清除与redis中某个字符串域关联的所有哈希?

标签 redis

例如我有User:1, User:2, User:3... User:2000。我想删除所有 User 以便重新开始。有没有一种方法可以在不知道确切 key 的情况下执行此操作,只是我想删除 User 域中的所有 key ?我有兴趣将此作为应用程序服务器启动任务的一部分。

最佳答案

比使用“keys”扫描所有键并通过正则表达式匹配删除更好的方法是使用标记机制,在服务器中维护一个 Redis SET 来保存关系 Tag-Keys,比如在这篇文章中: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 客户端通过两个操作来完成,例如通过使用 SMEMBERS :tag 获取标记“user”的成员:user 并使用 DEL key1 key2 .. 命令删除 key 。

关于redis - 如何清除与redis中某个字符串域关联的所有哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28796616/

相关文章:

python - 从本地主机连接到 Redis

redis - 与 Redis 和 Prometheus 集成

django - 用 AWS 基础设施替代 Celery 和 Redis 是什么?

redis - ServiceStack.Redis.RedisResponseException 使用 Redis 集群和 Twemproxy

php - Redis 在 docker 中作为 WordPress 的 session 存储

nosql - 我可以使用 Redis 作为唯一的数据库来为具有用户配置文件的中小型社交网站提供支持吗?

spring-boot - 在 spring boot 中启用 Redis 缓存

php - 如何禁用 Phalcon Redis 后端中使用的 _PHCR 键前缀

database - 如何使用此哈希通过 Redis 获取数据

php - Redis存储数据过期未设置过期时间