Last active
September 1, 2018 11:43
-
-
Save wcc526/c7c15e5c84c1628717f2f8c453b2c5d8 to your computer and use it in GitHub Desktop.
Redis排行版应用
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import string | |
import random | |
import redis | |
r = redis.StrictRedis(host='localhost',port=6379,db=0) | |
GAME_BOARD_KEY = 'game.board' | |
# 插入100条随机用户名和分数组成的记录,zadd方法表示操作的是有序列表 | |
for i in range(1000): | |
score = round((random.random() * 100),2) | |
user_id = ''.join(random.sample(string.ascii_letters,6)) | |
r.zadd(GAME_BOARD_KEY,score,user_id) | |
# 随机获取一个用户和他的得分,zrevrange表示从高到低对列表排序 | |
user_id, score = r.zrevrange(GAME_BOARD_KEY,0,-1,withscores=True)[random.randint(0.200)] | |
print user_id,score | |
# 获取全部记录条目数 | |
board_count = r.zcount(GAME_BOARD_KEY,0,100) | |
# 这个用户分属超过了多少用户 | |
current_count = r.zcount(GAME_BOARD_KEY,0,score) | |
print current_count,board_count | |
print 'Top 10' | |
print '-'*20 | |
# 获取排行版前10位的用户名和得分 | |
for user_id,score in r.zrevrangebyscore(GAME_BOARD_KEY,100,0,start=0,num=10,withscores=True): | |
print user_id,score | |
一个有序集合的元素数量可以达到2的32次方-1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment