Atomic operation of redis auto incrementing incr to set expiration time (Lua & PHP Implementation)

Time:2021-4-20

The auto increment operation of redis does not have a native expiration time setting. It can only auto increment first and then set the expiration time through expiration. If the expiration time setting fails under special circumstances, it will lead to business errors.

The following is based on PHP and Lua script to write a demo, so that self increment and expiration time become atomic operation, so as to avoid the above problems.

<?php
$redis = new Redis();
$result = $redis->connect('127.0.0.1');

$lua =  <<<LUA
        local key,ttl=KEYS[1],KEYS[2]

        if redis.call('EXISTS',key)==0 then  
          redis.call('SETEX',key,ttl,1)
          return 1
        else
          return tonumber(redis.call('INCR',key))
        end
LUA;


$sequence = $redis - > Eval ($Lua, ["test", 10], 2); // for Eval function, please check the official documentation
var_dump("RES:".$sequence);
$error = $redis->getLastError();
if($error){
    var_dump($error);
}
var_dump("VAL:".$redis->get("test"));
var_dump("TTL:".$redis->ttl("test"));

Recommended Today

Analysis of super comprehensive MySQL statement locking (Part 1)

A series of articles: Analysis of super comprehensive MySQL statement locking (Part 1) Analysis of super comprehensive MySQL statement locking (Part 2) Analysis of super comprehensive MySQL statement locking (Part 2) Preparation in advance Build a system to store heroes of the Three KingdomsheroTable: CREATE TABLE hero ( number INT, name VARCHAR(100), country varchar(100), PRIMARY […]