The key of distributed traffic limiting is to make the traffic limiting service global and unified. It can be implemented using Redis+Lua technology, through which high concurrency and high performance traffic limiting can be achieved.

Lua is a lightweight scripting language. It is an open source script written in the standard C language. It is designed to be embedded into applications and provide flexible extension and customization functions for applications.

Redis+Lua script to achieve distributed limiting ideas

We can use the way of Redia+Lua script to our distributed system for a unified full limited stream, Redis+Lua implementation of Lua script:

Local key = KEYS[1]

local now = tonumber(ARGV[1])

local ttl = tonumber(ARGV[2])

Local expired = Tonumber (ARGV[3])– maximum traffic

Local Max = tonumber(ARGV[4])– Clear expired data — remove all elements within the specified score range; expired means expired score– according to the current time milliseconds – timeout milliseconds, get expired time expired

Redis. Call (‘ zremrangebyScore ‘, key, 0, expired)- Gets the current number of elements in zset

local current = tonumber(redis.call(‘zcard’, key))

Local next = current + 1if next > Max then

return 0; Else — add a timestamp element to zset, [value,score]

Call (“zadd”, key, now, now) — resets zset expiration time in milliseconds for each access redis. Call (“pexpire”, key, TTL)

 return next

end

We can understand the above Lua script code as follows.

(1) In Lua script, there are two global variables used to receive the KEYS and other parameters passed by the Redis application, respectively: KEYS, ARGV;

(2) It is an array list when KEYS are passed in the application side, and the values in the array are obtained by index subscript in Lua script.

ARGV can be one or more independent parameters. However, ARGV is received in Lua script and obtained by array subscript.

(4) The above operation is in a Lua script, and because I am currently using Redis version 5.0 (Redis 6.0 supports multi-threading), the execution of the request is single thread, therefore, Redis+Lua processing is thread-safe, and atomic.

If an operation is indivisible and multithreaded safe, it is called an atomic operation.

Next, we can use the following Java code to determine if we need to limit the flow.