分頁(yè)場(chǎng)景:
在平常我們都是利用數(shù)據(jù)庫(kù)做分頁(yè),但在高并發(fā),數(shù)據(jù)庫(kù)可能就不能承載這樣的壓力,在高并發(fā)的場(chǎng)景下其實(shí)是不允許將請(qǐng)求直接打到數(shù)據(jù)庫(kù),那么可不可以用Redis做成緩存又做分頁(yè)呢?
下面我們來(lái)嘗試:
執(zhí)行命令
conposer require predis/predis
創(chuàng)建控制器:
php artisan make:controller xxx
創(chuàng)建function
/*
*author:MJ.shu
*time 2017/11/7 下午10:40
*All rights reserved
*/
const limit = 10;
function static test(string $key,int $page):array{
$res_num = Redis::zcard($key);
$max_page = ceil($res_num / self::limit);
if( $max_page < $page){
return ['code'=> 400,'msg'=>'page err','data'=>['result'=>[],'max_page'=>$max_page]];
}
$limit = (intval($page) * self::limit)-1;
$data = Redis::ZRANGE($key,$start,$limit);
$data = Redis::hmget('news',$data);
foreach ($data as $k=>$v){
$v = json_decode($v,true);
$new[] = $v;
}
return ['code'=>200,'data'=>['result'=>$new,'max_page'=>$max_page]];
第一步:
Redis::zcard($key); //返回有序集 key 的基數(shù)。
第二步:
ceil($res_num / self::limit); //計(jì)算總分頁(yè),數(shù)量/實(shí)現(xiàn)定義的常量
第三步:
//判斷請(qǐng)求頁(yè)數(shù)是否大于計(jì)算出的頁(yè)數(shù)
if( $max_page < $page){
return ['code'=> 400,'msg'=>'page err','data'=>['result'=>[],'max_page'=>$max_page]];
}
第三步:
計(jì)算條數(shù)
0 表示有序集第一個(gè)成員,所以要減1
$limit = (intval($page) * self::limit)-1;
第四步:
$data = Redis::ZRANGE($key,$start,$limit); //取得有序集合的值 ,有序集合里一般放的是數(shù)據(jù)id
第五步:
$data = Redis::hmget('news',$data); //從redis的hash表取得完整數(shù)據(jù)
第六步:
//循環(huán)結(jié)果集,將其解碼,組成新的數(shù)組,最后響應(yīng)API
foreach ($data as $k=>$v){
$v = json_decode($v,true);
$new[] = $v;
}
return ['code'=>200,'data'=>['result'=>$new,'max_page'=>$max_page]];