I'm reading the source code of redis 3.2. To expire keys actively, redis server calls activeExpireCycle function in the event loop.
This function has a parameter type
to specify the time limit. The type can be ACTIVE_EXPIRE_CYCLE_FAST
(fast cycle) or ACTIVE_EXPIRE_CYCLE_SLOW
(slow cycle). The time limit of fast cycle is hard coded to 1 millisecond (ACTIVE_EXPIRE_CYCLE_FAST_DURATION
). The time limit of slow cycle takes 25% of serverCron period, which is 25 milliseconds by default. So first cycle takes much shorter time than slow cycle.
What's more, the fast cycle is called in beforSleep
function, and the slow cycle is called in serverCron
function. I drew a diagram about these two calls in event loop.
I can't figure out the purpose of fast cycle. Why doesn't redis leave all the active expiring work to slow cycle?
UPDATE: I changed the upper diagram. Function serverCron doesn't be called in every loop. Redis executes serverCron() per 100 milliseconds by default.
答案 0 :(得分:1)
我在 redis 源代码中找到了注释。希望它对你有帮助(它会更积极地避免可以从键空间中删除的键使用太多内存):
// in https://github.com/redis/redis/blob/6.0/src/expire.c#L76
/* Try to expire a few timed out keys. The algorithm used is adaptive and
* will use few CPU cycles if there are few expiring keys, otherwise
* it will get more aggressive to avoid that too much memory is used by
* keys that can be removed from the keyspace.
*
* The function can perform more or less work, depending on the "type"
* argument. It can execute a "fast cycle" or a "slow cycle". The slow
* cycle is the main way we collect expired cycles: this happens with
* the "server.hz" frequency (usually 10 hertz).
*
* However the slow cycle can exit for timeout, since it used too much time.
* For this reason the function is also invoked to perform a fast cycle
* at every event loop cycle, in the beforeSleep() function. The fast cycle
* will try to perform less work, but will do it much more often.
*/