Redis上限排序集,列表或队列? [英] Redis Capped Sorted Set, List, or Queue?

查看:376
本文介绍了Redis上限排序集,列表或队列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人在Redis中实现任何形式的有上限的数据结构吗?我正在构建类似新闻提要的东西.提要会非常频繁地被操纵和读取,并且将其保存在Redis的分类集中对于我的用例来说是便宜又完美的选择.唯一的问题是每个提要仅需要n个项,并且我担心内存溢出,因此我想确保每个提要都不会超过n个项.用Lua在Redis中创建一个有上限的排序集合似乎很简单:

Has anyone implemented a capped data-structure of any kind in Redis? I'm working on building something like a news feed. The feed will wind up being manipulated and read from very frequently, and holding it in a sorted set in Redis would be cheap and perfect for my use case. The only issue is I only ever need n items per feed, and I'm worried about memory overflow, so I'd like to ensure each feed never gets above n items. It seems pretty trivial to make a capped sorted collection in Redis with Lua:

redis-cli EVAL "$(cat update_feed.lua)" 1 feeds:some_feed "thing_to_add", n

update_feed.lua的外观类似(未经测试):

Where update_feed.lua looks something like (without testing it):

redis.call('ZADD', KEYS[1], os.time(), ARGV[1])
local num = redis.call('ZCARD', KEYS[1])
if num > ARGV[2]:
    redis.call('ZREMRANGEBYRANK', KEYS[1], -n, -inf)

这一点都还不错,而且很便宜,但是看起来像是一件基本的事情,可以通过实例化仅包含n个存储桶的排序集来便宜得多.我找不到在Redis中执行此操作的方法,所以我想我的问题是:我错过了什么吗?如果没有,为什么即使在Redis中运行基本的Lua,Redis中也没有此结构在我描述的脚本中,似乎这将是一个足够典型的用例,应该作为Redis数据结构的一个选项来实现?

That's not bad at all, and pretty cheap, but it seems like such a basic thing that could be doable much more cheaply by instantiating the sorted set with only n buckets to begin with. I can't find a way to do that in redis, so I guess my question is: did I miss something, and if I didn't, why is there no structure for this in redis, even if it just ran the basic Lua script I described, it seems like it would be a typical enough use-case that it ought to be implemented as an option for redis data structures?

推荐答案

如果使用 LTRIM ,则可以使用是一个列表.

You can use LTRIM if it is a list.

文档摘录.

LPUSH mylist someelement
LTRIM mylist 0 99

这对命令将在列表中推送一个新元素,同时确保列表的长度不会超过100个元素.例如,在使用Redis存储日志时,这非常有用.重要的是要注意,当以这种方式使用LTRIM时,它是O(1)运算,因为在通常情况下,列表的尾部仅删除一个元素.

This pair of commands will push a new element on the list, while making sure that the list will not grow larger than 100 elements. This is very useful when using Redis to store logs for example. It is important to note that when used in this way LTRIM is an O(1) operation because in the average case just one element is removed from the tail of the list.

这篇关于Redis上限排序集,列表或队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆