A common design pattern in redis when handling lists is:
redis_server.lpush(list_name, element)
redis_server.ltrim(list_name, 0, 99)
(used python syntax to illustate it)
What to do if one needs to retrieve all the values beyond index 99, before invoking ltrim
? One way to do it is as follows, but is there a faster way to do it?
redis_server.lpush(list_name, element)
list_length = redis_server.llen(list_name)
extra = list_length - 100
while (extra > 0):
item = redis_server.lpop(list_name)
#do something with the item
extra = extra - 1
redis_server.ltrim(list_name, 0, 99)
A first solution would be to get all extra items in one request, using LRANGE :
redis_server.lpush(list_name, element) items = redis_server.lrange(list_name, 100, -1) # do something with the items redis_server.ltrim(list_name, 0, 99)
A second solution, a bit more complex but maybe faster (would need to be confirmed by a test, it's not certain) as it requires only one request instead of two, would be to write a Lua script and to send it using EVAL and EVALSHA . But you probably don't need it, the first is certainly fast enough.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.