一.需求


记录用户uid和上次操作时间;并清除5分钟以前的数据.用redis的一个key实现.本打算用hash,但hash类型在过期5分钟以前的数据时颇为麻烦.

 

二.代码实现

class LastLoginService
{
    const CACHE_KEY_FIVE = 'last.login.five';
    const LAST_MINUTE_FIVE = 5;

    /**
     * @param $user_id
     */
    public static function loginAtFive($user_id)
    {
        self::clearExpired();
        Redis::zadd(self::CACHE_KEY_FIVE, time(), $user_id);
    }

    /**
     * 返回user_id数组,按上次操作时间,降序排
     */
    public static function getAllFiveOnline()
    {
        self::clearExpired();
        return Redis::zrevrange(self::CACHE_KEY_FIVE, 0, -1, 'WITHSCORES');
    }

    /**
     * 清除过期数据
     */
    public static function clearExpired()
    {
        Redis::zremrangebyscore(self::CACHE_KEY_FIVE, 0, time() - self::LAST_MINUTE_FIVE * 60);
    }
}

  

相关文章:

  • 2021-08-14
  • 2021-10-06
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-07
  • 2021-06-02
  • 2021-11-21
  • 2021-09-27
相关资源
相似解决方案