This article mainly introduces the use of Redis to achieve the user points leaderboard, including a PHP script to operate the example, the need for friends can refer to the following
The leaderboard feature is a very common requirement. Using the attributes of an ordered collection in Redis to achieve a leaderboard is a good and fast choice.
The general leaderboard is effective, such as the "User standings". If the results are not always in line with the overall list, it may be the top of a few old users, for new users, it is really frustrating.
First of all, a "Today's standings," The collation is today users add more points from the less.
Then, when users add points, they operate an ordered set of points added on the day of recording.
Assuming today is April 01, 2015, the user with the UID of 1 has added 5 points for an operation.
The Redis command is as follows:
Let's say that several other users have added points as well:
Take a look at the data in the Ordered collection rank:20150401 (the Withscores parameter can be supplied with the score for the element):
Zrange rank:20150401 0-1 Withscores
Get TOP10 by score from high to Low:
Zrevrange rank:20150401 0 9 Withscores
Because there are only three elements, the data is queried.
If you record the day's leaderboard every day, then the list of other tricks is simple.
such as "Yesterday's standings":
Achieve "Last week's standings" by using a combination of multiple days of integration:
This merges the 7-day integration record into the ordered set Rank:last_week. Weight factor WEIGHTS If not given, the default is 1. In order not to hide the details, deliberately written.
So the query for last week's standings TOP10 is:
"Monthly Standings", "Quarterly Charts", "annual charts" and so on.
A simple implementation of the PHP version is given below. Using Redis to rely on PHP extension Phpredis, the code also relies on the Carbon library for processing time. The code is very small, so don't hit the comment.
<?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::P refix. Date (' Ymd '); return $this->redis->zincrby ($key, $scores, $member); } protected function Getonedayrankings ($date, $start, $stop) { $key = self::P refix. $date; return $this->redis->zrevrange ($key, $start, $stop, true);
Redis implements user points leaderboard