Use redis achieve leaderboards

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u011510825/article/details/85394592

Leaderboards is a very common needs.

Imagine in a game, there are millions of player data, if you now need to organize a top 20 ranking players based on experience, how would you do it?

You can not order by + limit to achieve

select * from game_socre order by score desc limit 0,20  

To achieve sound and rapid rankings are selected using Redis properties in ordered sets.

Under first introduced, several commands will be used and their effects:

Details Tell me what network ( Redis Chinese)

zrange view leaderboards (ascending)

zrevrange view leaderboards (descending)

Adding a data zadd

zrem delete data

zrank get ranked (in ascending order)

zrevrank get ranked (in descending order)

 

Knowing command, we can try to play a little longer

127.0.0.1:6379> zrange rank_name 0 -1 withscores
(empty list or set)

Check rank_name ranking table is empty, because we have not ordered set of rank_name this add, 0, -1 means to find all, withscores represent a value.

We add some data using zadd

127.0.0.1:6379> zadd rank_name 10 zhangsan
(integer) 1
127.0.0.1:6379> zadd rank_name 5 lisi
(integer) 1
127.0.0.1:6379> zadd rank_name 100 wangwu
(integer) 1

Check again

127.0.0.1:6379> zrange rank_name 0 -1 withscores
1) "lisi"
2) "5"
3) "zhangsan"
4) "10"
5) "wangwu"
6) "100"
127.0.0.1:6379> zrevrange rank_name 0 -1 withscores
1) "wangwu"
2) "100"
3) "zhangsan"
4) "10"
5) "lisi"
6) "5"

Now I want to see alone, zhangsan and lisi rankings

127.0.0.1:6379> zrank rank_name zhangsan
(integer) 1
127.0.0.1:6379> zrank rank_name lisi
(integer) 0

Here we must note, redis ranking is zero-based, so the general will add 1, comparing no one said the first 0.

Update operation is relatively simple, and can be used directly zadd coverage. Not recommended for use under high concurrency. Such as voting such league tables, the general use of atomic increment operation, ensure data accuracy

127.0.0.1:6379> zincrby rank_name 1 wangwu
"101"
127.0.0.1:6379> zrevrange rank_name 0 -1 withscores
1) "wangwu"
2) "101"
3) "zhangsan"
4) "10"
5) "lisi"
6) "5"

Day rankings, weekly charts, you can set the basic monthly leaderboard key + time, as rank_name_20181230.

 

to sum up:

Redis ordered set is a very efficient data structure, may be substituted for some of the database operation difficult to achieve. It's a typical scenario that list, you can quickly get the user's ranking by ZRANK, you can quickly get a list of users TOP N by ZRANGE, their complexity is O (log (N)), database queries can be used as a substitute greatly improve performance.

 

 

Guess you like

Origin blog.csdn.net/u011510825/article/details/85394592
Recommended