Unique scoring for redis leaderboard

2019-04-14 16:20发布

问题:

I am using redis to create a leaderboard and trying to figure out a nice way to deal with players who achieve the same high score (players with the same high score should be ordered by who achieved that high score first)

I had thought of doing the following...

zadd leaderboard highscore.timestamp player_id.attempt_number

However, when I do zrevrange the timestamps are obviously going to be in the incorrect order.

Example input:

zadd leaderboard 20.123 5.1
zadd leaderboard 20.125 5.2
zadd leaderboard 20.012 5.3
zadd leaderboard 21.024 5.4

Output:

zrevrange leaderboard 0 -1
5.4
5.2
5.1
5.3

Desired output:

5.4
5.3
5.1
5.2

回答1:

One option would be to do zadd leaderboard highscore.(Long.MAX_VALUE - timestamp) player_id.attempt_number (change Long.MAX_VALUE to whatever is a reasonable highest possible value for your timestamp - A signed 64 bit int will store about 300 million years worth of miliseconds, so that might not be needed)

EDIT: Don't forget to add leading zeroes :)



标签: redis