使用 Redis 实现排行榜功能

回复 星标
更多
使用 Redis 实现排行榜功能
.
.
.
.
.
.

排行榜功能是一个很普遍的需求。使用 Redis 中有序集合的特性来实现排行榜是又好又快的选择。

一般排行榜都是有实效性的,比如“用户积分榜”。如果没有实效性一直按照总榜来排,可能榜首总是几个老用户,对于新用户来说,那真是太令人沮丧了。

首先,来个“今日积分榜”吧,排序规则是今日用户新增积分从多到少。那么用户增加积分时,都操作一下记录当天积分增加的有序集合。

假设今天是 2015 年 04 月 01 日,UID 为 1 的用户因为某个操作,增加了 5 个积分。

Redis 命令如下:

ZINCRBY rank:20150401 5 1

假设还有其他几个用户也增加了积分:

ZINCRBY rank:20150401 1 2ZINCRBY rank:20150401 10 3

看看现在有序集合 rank:20150401 中的数据(withscores 参数可以附带获取元素的 score):

ZRANGE rank:20150401 0 -1 withscores
1) "2"
2) "1"
3) "1"
4) "5"
5) "3"
6) "10"

按照分数从高到低,获取 top10:

ZREVRANGE rank:20150401 0 9 withscores
1) "3"
2) "10"
3) "1"
4) "5"
5) "2"
6) "1"

因为只有三个元素,所以就查询出了这些数据。

如果每天记录当天的积分排行榜,那么其他花样百出的榜单也就简单了。

比如“昨日积分榜”:

ZREVRANGE rank:20150331 0 9 withscores

利用并集实现多天的积分总和,实现“上周积分榜”:

ZUNIONSTORE rank:last_week 7 rank:20150323 rank:20150324 rank:20150325 
rank:20150326 rank:20150327 rank:20150328 rank:20150329 WEIGHTS 1 1 1 1 1 1 1

这样就将 7 天的积分记录合并到有序集合 rank:last_week 中了。权重因子 WEIGHTS 如果不给,默认就是 1。为了不隐藏细节,特意写出。

那么查询上周积分榜 Top10 的信息就是:

ZREVRANGE rank:last_week  0 9 withscores

“月度榜”、“季度榜”、“年度榜”等等就以此类推。

下面给出一个 PHP 版的简单实现。使用 Redis 依赖于 PHP 扩展PhpRedis,代码还依赖于Carbon库,用于处理时间。代码量很少,所以就不敲注释了。

<?php
namespace Blog\Redis;
use \Redis;
use Carbon\Carbon;
class Ranks {
    const PREFIX = 'rank:';
    protected $redis = null;
    public function __construct(Redis $redis) {
        $this->redis = $redis;
    }
    public function addScores($member, $scores) {
        $key = self::PREFIX . date('Ymd');
        return $this->redis->zIncrBy($key, $scores, $member);
    }
    protected function getOneDayRankings($date, $start, $stop) {
        $key = self::PREFIX . $date;
        return $this->redis->zRevRange($key, $start, $stop, true);
    }
    protected function getMultiDaysRankings($dates, $outKey, $start, $stop) {
        $keys = array_map(function($date) {
            return self::PREFIX . $date;
        }, $dates);

        $weights = array_fill(0, count($keys), 1);
        $this->redis->zUnion($outKey, $keys, $weights);
        return $this->redis->zRevRange($outKey, $start, $stop, true);
    }
    public function getYesterdayTop10() {
        $date = Carbon::now()->subDays(1)->format('Ymd');
        return $this->getOneDayRankings($date, 0, 9);
    }
    public static function getCurrentMonthDates() {
        $dt = Carbon::now();
        $days = $dt->daysInMonth;

        $dates = array();
        for ($day = 1; $day <= $days; $day++) {
            $dt->day = $day;
            $dates[] = $dt->format('Ymd');
        }
        return $dates;
    }
    public function getCurrentMonthTop10() {
        $dates = self::getCurrentMonthDates();
        return $this->getMultiDaysRankings($dates, 'rank:current_month', 0, 9);
    }
}

去除 Carbon 版本的 Ranks 类:

<?php
namespace Org;
use \Redis;
class Ranks {
    const PREFIX = 'rank:';
    protected $redis = null;
    public function __construct(Redis $redis) {
        $this->redis = $redis;
    }
    public function addScores($member, $scores) {
        $key = self::PREFIX . date('Ymd');
        return $this->redis->zIncrBy($key, $scores, $member);
    }
    protected function getOneDayRankings($date, $start, $stop) {
        $key = self::PREFIX . $date;
        return $this->redis->zRevRange($key, $start, $stop, true);
    }
    protected function getMultiDaysRankings($dates, $outKey, $start, $stop) {
        $keys = array_map(function($date) {
            return self::PREFIX . $date;
        }, $dates);

        $weights = array_fill(0, count($keys), 1);
        $this->redis->zUnion($outKey, $keys, $weights);
        return $this->redis->zRevRange($outKey, $start, $stop, true);
    }
    public function getYesterdayTop10() {
        $yesterday = date('Ymd',strtotime('-1 day'));
        return $this->getOneDayRankings($date, 0, 9);
    }
    public static function getCurrentMonthDates() {
        $days = 30;
        $current_year = date('Y');
        $current_month = date('m');
        switch ($current_month) {
            case '01':
            case '02':
            case '05':
            case '07':
            case '08':
            case '10':
            case '12':
                $days = 31;
                break;
            case '04':
            case '06':
            case '09':
            case '11':
                $days = 30;
                break;
            case '02':
                $days = $this->isLeapYear($current_year) ? 29 : 28;
                break;
        }
        $dates = array();
        for ($day = 1; $day <= $days; $day++) {
            $dates[] = date('Ymd', strtotime($current_year.'-'.$current_month.'-'.$day));
        }
        return $dates;

    }
    public function getCurrentMonthTop10() {
        $dates = self::getCurrentMonthDates();
        return $this->getMultiDaysRankings($dates, 'rank:current_month', 0, 9);
    }
    /**
     * 闰年计算方法;能被4整除即为闰年,被100整除而不能被400整除的为平年,能被100整除也可被400整除的为闰年
     */
    private function isLeapYear($year) {
        if( ($year%4==0) && ($year % 100!=0)||($year % 400==0) ) {
            return true;
        } else {
            return false;
        }
    }
}
新窗口打开 关闭