利用redis有序集合实现实时更新阅读排行榜

获取代码:

    /**
     * 获取排行榜
     */
    public function getHotImage($num=6)
    {
        //获取redis排行榜有序集合
        $hotImageIds = $this->getHotImageIds($num);
        $ids = implode(',',$hotImageIds);
        $redisKey = CommonConst::MODULE_ID . __METHOD__ . md5($ids);
        if ($this->publicRedis->exists($redisKey)) {
            return json_decode($this->publicRedis->get($redisKey), true);
        }

        $pic_list = $this->publicDao->getListByIds($ids);
        if($pic_list['data']){
            $this->publicRedis->setex($redisKey, 10 * 24 * 3600, json_encode($pic_list));
        }
        return $pic_list;
    }

    /**
     * 获取排行榜ID
     */
    public function getHotImageIds($num=6)
    {
        //获取redis排序集合
        $hot_redisKey = CommonConst::MODULE__ID .'_'. __METHOD__;

        $hotImageIds = array();
        if ($this->publicRedis->exists($hot_redisKey)) {
            return $this->publicRedis->zRevRange($hot_redisKey,0,-1);
        }
        $images = $this->publicDao->getList(array('status'=>1),array('view_num'=>'desc'),array(0,$num));

        if($images){
            foreach($images as $val){
                $this->publicRedis->zAdd($hot_redisKey, $val['view_num'], $val['id']);
            }
            $hotImageIds =  $this->publicRedis->zRevRange($hot_redisKey,0,-1);
        }
        return $hotImageIds;
    }

更新点击量

    /**
     * 增加点击数
     */
    public function addHits($image_id,$now_hits,$hits=1){
        $ret = $this->publicDao->update(array('id'=>$image_id),array('view_num'=>$now_hits+$hits));
        if($ret){
            $hot_redisKey = CommonConst::MODULE_ID . '_Bn_ImagesService::getHotImageIds';
            //获取现有点击数
            $score =  $this->publicRedis->zScore($hot_redisKey,$image_id);
            if($score){
                //如果有,incr增加1
                $this->publicRedis->zIncrBy($hot_redisKey,$hits,$image_id);
            }else{
                //查询排行列表是否有小于等于当前播放量的数据
                $less_member = $this->publicRedis->zRangeByScore($hot_redisKey,0,$now_hits,array('limit' => array(0, 1)));
                if($less_member){
                    //删除小于当前播放量的元素
                    $this->publicRedis->zDelete($hot_redisKey,$less_member[0]);
                    //将当前元素增加至集合
                    $this->publicRedis->zAdd($hot_redisKey, $now_hits+$hits,$image_id);
                }

            }

        }
        return $ret;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值