php How to set time in redis: 1. Cancel the survival time and set the key’s survival time to permanent, which is PERSIST. The code is [PERSIST session:captcha]; 2. Use TTL to see the survival time of a key. Command, code is [TTL session:captcha].
php redis method of setting time:
Redis provides survival time for keys, when the survival time is not specified , the survival time is permanent. Redis will automatically delete this key after the time expires. You can use the EXPIRE command, and the time unit is seconds. If a key is set to have a limited survival time, it will be set to permanent again when the SET key is reassigned:
SET session:captcha sd2a EXPIRE session:captcha 600
Cancel the survival time, and The key's lifetime is set to permanent, which is PERSIST:
PERSIST session:captcha
Use the TTL command to view the lifetime of a key. -1 means permanent or deleted upon expiration.
TTL session:captcha
The survival time will not be changed during Redis' INCR, LPUSH, HSET, ZREM and other commands.
If you want to control the time accurately to the millimeter, you need PEXPIRE, and use PTTL to check the remaining time.
What if you want to give an expiration time instead of how many seconds it will expire? You need EXPIREAT and PEXPIREAT. The parameter of EXPIREAT is the timestamp of expiration (seconds), and the parameter of PEXPIREAT is the expiration time of timestamp (milliseconds)
SET session:captcha sd2a EXPIREAT session:captcha 1399902009 PEXPIREAT session:captcha 1399902009000
Application scenario 1: Access frequency limit: We limit each user to 1 minute Can browse 10 pages. The pseudo code is as follows:
$isExists = EXISTS limit:user1:192.168.1.2 if($isExists){ $num = INCR limit:user1:192.168.1.2 if($num > 10){ print '超过限制' exit } }else{ MULTI INCR limit:user1:192.168.1.2 EXPIRE limit:user1:192.168.1.2 60 EXEC }
The reason why we use transactions is because after joining, after executing INCR limit:user1:192.168.1.2 and before executing EXPIRE limit:user1:192.168.1.2 60, the client is closed. Then the key and value will be persisted. And this ID can only be accessed 10 times in a lifetime. That's too bad.
If you want to know more about programming learning, please pay attention to the php training column!
The above is the detailed content of php redis any set time. For more information, please follow other related articles on the PHP Chinese website!