Home  >  Article  >  Database  >  What is the difference between setex command and set command in redis

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

王林
王林forward
2021-02-07 09:28:532366browse

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

SETEX command Redis string (String) command

SETEX key seconds value

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');  # 设置生存时间

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"

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete