首页 文章

Redis键未到期 - Laravel,Predis

提问于
浏览
7

我正在使用Laravel 5.4Predis和最新的Redis(或Redis for Windows) .

密钥保存没有问题 . 所以,我怀疑这是一个配置问题 .

问题是他们没有到期 . The key is reused until it expires...similar to how a session works.

如果它不存在,我创建一次密钥 . 在同样的逻辑中,我然后设置到期时间 .

In the Controller, I have

use Illuminate\Support\Facades\Redis;

在其中一个函数中, Get the connection instance

$redis = Redis::connection();

在创建密钥之前,我检查存在(简化)然后创建并设置到期 .

if(!$redis->exists($some_unique_key))
{
   //set the key
   $redis->set($some_unique_key, 'Some Value'));
   //set the expiration
   //I understand this means expire in 60s.
   $redis->expire($some_unique_key,60); 
}

为什么它不会到期钥匙?

正如我所提到的,其他一切都有效 . 如果我监视,我会看到密钥更新没有问题,并且可以查询它 .

为了记录,我读过:

Laravel文档到期时没有任何内容:

UPDATE 1

调查设置(更新)密钥的可能原因会重置到期日

UPDATE 2

使用@ for_thestack的推理(在REDIS命令中)来提出解决方案 . 用代码查看我的回答 . 随意upvote @for_thestack :)

3 回答

  • 3

    某些其他进程可能会调用 SET 来更新键值对,在这种情况下,将删除到期日期 .

    // set expiration
    EXPIRE key expiration_in_seconds
    // update key-value pair with no expiration
    SET key new_value
    // now, expiration has been reset, and the key won't be expired any more
    

    为了保持过期,当您更新键值对时,应该使用过期参数调用 SET .

    // get TTL, i.e. how much time left before the key will be expired
    TTL key
    // update with expiration parameter
    SET key new_value EX ttl
    

    您可以将两个命令包装到lua脚本中以使其成为原子 . 而且,当您调用 TTL 时,您还需要注意密钥不存在的情况 . 有关详细信息,请参阅文档

  • 4

    对于那些使用Laravel的人,可以使用EX param(expire resolution)ttl:

    Redis::set($key, $val, 'EX', 35);
    

    在预测中,你可以使用相同的,实际上Laravel使用了引擎盖下的预测 .

  • 2

    由于@for_stack为我提供了逻辑(在REDIS命令和逻辑中),我接受了他的贡献作为答案 .

    我的问题是,我不知道密钥,重置到期日 . 因此,正如@for_stack所解释的那样,使其工作包括:

    如果密钥存在,

    • 获取TTL
      更新密钥后
    • ,将到期时间设置为我得到的TTL(1)

    这意味着整体TTL不精确 . 在我获得(1)中的TTL值到更新它的时间之间需要毫秒或微秒的余量....这对我来说很好!

    因此,对于我的Laravel(PHP),Predis场景,我执行以下操作:

    在某些相关点,代码中更高:

    //get ttl - time left before expiry
    $ttl = $redis->ttl($some_unique_key);
    

    然后,无论我在哪里更新值,我都会在设置值后设置到期时间 . The logic for creating the key(in my question) remains correct and unchanged.

    //***note that I am UPDATING a key. Checking if it exists then I update
    if($redis->exists($some_unique_key))
    {
       //set/up the key
       $redis->set($some_unique_key, 'Some New, Updated, Value'));
    
       //Do some work   
    
       //set the expiration with the TTL value from (1)
       $redis->expire($some_unique_key,$ttl); 
    }
    

    完美的工作!

相关问题