The increment operation in Redis does not have a native set of expiration time. Instead, it has to increment the expiration time first and then expire it through expire. Failure to set the expiration time in a special case will cause a business error.
Here’s a DEMO based on PHP and Lua scripting that makes auto-increment and expiration time atomic operations to avoid this problem.
<? 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); Var_dump ("RES:".$sequence); $error = $redis->getLastError(); if($error){ var_dump($error); } var_dump("VAL:".$redis->get("test")); var_dump("TTL:".$redis->ttl("test"));