Redis generates distinctive, numeric only codes

Mondo Technology Updated on 2024-02-20

Description of the requirements

When developing a coupon system or ticketing system, it is often necessary to generate a pure digital code, and the coupon code requires: 12 digits of pure number, irregular, and not repeated.

Below I provide an idea, using the list data type of Redis, lpop+rpush to maintain a queue of 10,000 codes.

Queue data structure

Maintain the number of 10,000 coupon codes, which can be adjusted according to the actual situation of the project.

array

Client

The LPOP method of Redis takes out a specified number of coupon codes.

If the number of coupon codes in the queue is insufficient, there is a fallback plan, and the insufficient part is filled with random numbers.

Knowledge points: LPOP is atomic, and in high-concurrency scenarios, even if multiple users get the coupon code at the same time, it will be executed one by one in order of priority, so as to ensure that the coupon code taken out by each user is not repeated.

@从队列中取出指定数量的券码.

param $num the number of coupon codes.

return array returns an array of coupon codes.

function getcode($num)

If there is not enough coupon code left in the queue, the insufficient part will be randomly generated.

if(count($codearr)

return $codearr;

Maintain the number of queue coupon codesThere is a script that regularly checks the queue and finds out how many coupon codes are consumed, so it rpushes multiple coupon codes into it.

The newly generated random number coupon code should be compared with the database, and if the coupon code already exists, it should be discarded and regenerated.

Knowledge points: rpush is also atomic, when rpush data, try to insert multiple coupon codes at a time to reduce the queuing time of the user.

*Example.

codedata=$redis->lrange($key,0,-1);Take out all the data in the coupon code queue.

codedata=!is_array($codedata)?[codedata;

len=count($codedata);

diff=10000-$len;How many are missing.

validarr=;Valid verification code.

if($diff>0)

filterarr="'".$code."'";

validarr=$code;

if(count($filterarr)==0)

Find out if the coupon code has been used.

usedarr=;

filter_str=implode(",",$filterarr);

sql="select distinct `code` from `user_code` where `code` in ()";

tmpdata=db::query($sql);

foreach($tmpdata as $k=>$v)

unset($tmpdata);

validarr=array_diff($validarr,$usedarr);Subtract what is already used in the database.

if(count($validarr)

Project inventory

The ticketing system of the author's company, using this coupon code solution, has been running stably for many years with tens of millions of annual data.

Related Pages