Home > Database > Redis > body text

What is the difference between setex command and set command in redis

王林
Release: 2021-02-07 09:28:53
forward
2381 people have browsed it

What is the difference between setex command and set command in redis

Introduction:

The Redis Setex command sets the value and expiration time for the specified key. If key already exists, the SETEX command will replace the old value.

The basic syntax of the redis Setex command is as follows:

redis 127.0.0.1:6379> SETEX KEY_NAME TIMEOUT VALUE
Copy after login

SETEX command Redis string (String) command

SETEX key seconds value
Copy after login

Associate the value to the key, and set the key's survival time to seconds (in seconds).
If the key already exists, SETEX will overwrite the old value;

This command is similar to the following two commands:

$redis->SET('key', 'value');
$redis->EXPIRE('key','seconds');  # 设置生存时间
Copy after login

The difference is that SETEX is an atomic operation , the two actions of associating the value and setting the survival time will be completed at the same time. This command is very practical when Redis is used as a cache.

Return value:
Return OK when the setting is successful.
When the seconds parameter is illegal, an error is returned.

# 情况1:key不存在
$redis->SETEX('cache_user_id', 60,100001);//bool(true)
echo $redis->GET('cache_user_id');  # 值 //"100001"

echo $redis->TTL('cache_user_id');  # 剩余生存时间 //int(56)

# 情况2:key已经存在,key被覆写
$redis->SET('cd', "timeless"); //bool(true);
$redis->SETEX('cd', 3000,"goodbye my love"); //bool(true);
echo $redis->GET('cd');//"goodbye my love"
Copy after login

Related recommendations: redis database tutorial

The above is the detailed content of What is the difference between setex command and set command in redis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template