您的位置:首页 > 数据库 > Redis

redis有序集合的一个应用

2017-07-27 13:07 260 查看

一.需求

记录用户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);
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: