22
33namespace App ;
44
5- use Illuminate \Support \Facades \Redis ;
5+ use Illuminate \Support \Facades \Cache ;
66
77class Trending
88{
@@ -13,7 +13,10 @@ class Trending
1313 */
1414 public function get ()
1515 {
16- return array_map ('json_decode ' , Redis::zrevrange ($ this ->cacheKey (), 0 , 9 ));
16+ return Cache::get ($ this ->cacheKey (), collect ())
17+ ->sortByDesc ('score ' )
18+ ->slice (0 , 5 )
19+ ->values ();
1720 }
1821
1922 /**
@@ -31,19 +34,35 @@ private function cacheKey()
3134 *
3235 * @param Thread $thread
3336 */
34- public function push ($ thread )
37+ public function push ($ thread, $ increment = 1 )
3538 {
36- Redis::zincrby ($ this ->cacheKey (), 1 , json_encode ([
39+ $ trending = Cache::get ($ this ->cacheKey (), collect ());
40+
41+ $ trending [$ thread ->id ] = (object ) [
42+ 'score ' => $ this ->score ($ thread ) + $ increment ,
3743 'title ' => $ thread ->title ,
3844 'path ' => $ thread ->path (),
39- ]));
45+ ];
46+
47+ Cache::forever ($ this ->cacheKey (), $ trending );
48+ }
49+
50+ public function score ($ thread )
51+ {
52+ $ trending = Cache::get ($ this ->cacheKey (), collect ());
53+
54+ if (!isset ($ trending [$ thread ->id ])) {
55+ return 0 ;
56+ }
57+
58+ return $ trending [$ thread ->id ]->score ;
4059 }
4160
4261 /**
4362 * 重置所有热门线程.
4463 */
4564 public function reset ()
4665 {
47- Redis:: del ($ this ->cacheKey ());
66+ return Cache:: forget ($ this ->cacheKey ());
4867 }
4968}
0 commit comments