Get the App
SLTechnology News&Howtos  ›  Database  › 

What are the methods of realizing speed limiter with redis

Shulou Source: shulou.com Published: 2022-06-01 21:39:35 09月18日 Update

What are the ways to realize the speed limiter in redis? Many people don't know much about it. Today, in order to let you know more about the method of realizing the speed limiter in redis, I have summarized the following contents. Let's look down together.

Several ways to realize the speed limiter in redis.

GET + INCR + EXPIRE

Get the current value of key first, then perform INCR increment 1 if the limit is not exceeded, and initialize the key and expiration time with redis's transaction if key does not exist.

Pseudo code:

Count = redis.GET (key) if redis return nil {redis.MULTI redis.INCR (key) redis.EXPIRE (key, expire_time) redis.EXEC count = 1} if count > limit {return out of limit} else {redis.INCR (key)}

Problems under high concurrency:

If 10 concurrent programs execute GET at the same time and return nil, then all 10 concurrent programs will execute redis transactions to increase the key by one, but each program has a count value of 1. If the limit setting value is less than 10, then the actual execution of the program exceeds the limit. If you check the redis assignment to count again after executing the transaction, each program may return 10, so no program can continue execution.

When key already exists, the logic of GET followed by INCR may also have more programs actually executed than limit.

INCR + EXPIRE

INCR first. If the value is 1, it means that key has just set it. Then execute EXPIRE at this time.

Pseudo code:

Count = redis.INCR (key) if count = = 1 {redis.EXPIRE (key, expire_time)} if count > limit {return out of limit}

Use with caution

If the program dies after the INCR and does not execute the EXPIRE, then the key does not have an expiration time, depending on the requirements.

Lua script

Local currentcurrent = redis.call ("incr", KEYS [1]) if tonumber (current) = = 1 then redis.call ("expire", KEYS [1], 1) end

On the redis to achieve speed limiter methods to share here, of course, not only the above and everyone's analysis methods, but the editor can ensure its accuracy is absolutely no problem. I hope that the above content can have a certain reference value for everyone, and can be put into practice. If you like this article, you might as well share it for more people to see.

Tags: Program speed limit speed limiter limit method transaction code content situation time problem application of knowledge value accuracy method at the same time practice article way more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Tech Info OPPO Reno Linux Docker