简体   繁体   中英

Redis: How is the result of KEYS * sorted?

I have a very simple php redis application which creates keys at certain events. All the keys are just counters and have an expire time of 24 hours. Basically a rolling window of 24 hours for every key to gather some statistics.

if ($redis->exists($key)) {
    $redis->incr($key); 
}
else {
    $redis->set($key, '1');
    $now = time(); // current timestamp
    $redis->expireAt($key, $now + 86400);
}

When I extract an overview of all my keys with $list = $redis->keys("*"); (or in a redis-cli console with keys * ), I would suspect a chronological order by creation date. However this is not case. Neither are they ordered alphabetically, by value...

So my question is, how is this list sorted?

First of all, don't use keys * it is debug function not designed for a production, you can kill your server... If you need enumerate all keys in DB in safe way, use SCAN function with LIMIT .

Anyway results of keys or scan is not sorted in any manner, order of results related to internal memory structure of redis's hashtable.

About your php script, you can do it by a single command, without exists set expireat just run:

SET key 1 EX 86400 NX

EX 86400 mean expire in 86400 (1 day) seconds from now

NX mean create a key only if it doesn't exists.

If this command return (nil) run regular INCR key its mean that the key already exists. BTW INCR command will not remove your expire settings.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM