首页 > 代码库 > Redis 排行榜 自己简单练习

Redis 排行榜 自己简单练习

<?php
class Ranks{
	const PREFIX = ‘zhengban‘;
	protected $redis = ‘‘;
	/*
	初始化
	 */
	public function __construct(redis $redis){
		$this->redis = $redis;
	}
	/*
	添加到排行榜
	 */
	public function addScores($gameid,$score){
		$key = self::PREFIX . date(‘Ymd‘);
		return $this->redis->zIncrBy($key, $score, $gameid);
	}
	/*
	获取特定一天的排行榜数据
	返回一维数组,key是gameid,value是score
	 */
	public function getOneDayRankings($date,$start,$end){
		$key = self::PREFIX . $date;
        return $this->redis->zRevRange($key, $start, $end, true);
	}
	/*
	获取几天数据的排行榜
	 */
	public function getMultiDaysRankings($dates,$start,$end){
		$outKey = null;
		foreach ($dates as $v){
			$keys[] = self::PREFIX . $v;
		}
        //$weights = array_fill(0, count($keys), 1);
        //$this->redis->zUnion($outKey, $keys,$weights);
        $this->redis->zUnion($outKey, $keys);
        return $this->redis->zRevRange($outKey, $start, $end, true);
	}
}

	$host = "192.168.1.114";
	$port = 6379;
	$pwd = "123456";
	$redis = new Redis();
	if ($redis->connect($host, $port) == false) {
		exit(‘{"result":"-1"}‘);   //连接失败
	}
	/* AUTH的密码 */
	if ($redis->auth($pwd) == false) {
		exit(‘{"result":"-2"}‘);   //认证失败
	}

	$Ranks = new Ranks($redis);
	//$Ranks->addScores(12,1);
	$order = $Ranks->getMultiDaysRankings(array(20151021,20151022,20151020),0,9);
	var_dump($order);

	

 

Redis 排行榜 自己简单练习