22
33namespace App ;
44
5- use Illuminate \Support \Facades \Redis ;
5+ use Illuminate \Support \Facades \Cache ;
66
77class Trending
88{
99 /**
10- * 获取所有热门线程.
10+ * 获取所有热门线程
1111 *
1212 * @return array
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 /**
20- * 获取缓存键名.
23+ * 获取缓存键名
2124 *
2225 * @return string
2326 */
@@ -27,23 +30,40 @@ private function cacheKey()
2730 }
2831
2932 /**
30- * 将新线程推送到热门线程列表.
33+ * 将新线程推送到热门线程列表
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+
40+ $ trending = Cache::get ($ this ->cacheKey (), collect ());
41+
42+ $ trending [$ thread ->id ] = (object ) [
43+ 'score ' => $ this ->score ($ thread ) + $ increment ,
3744 'title ' => $ thread ->title ,
38- 'path ' => $ thread ->path ()
39- ]));
45+ 'path ' => $ thread ->path (),
46+ ];
47+
48+ Cache::forever ($ this ->cacheKey (), $ trending );
49+ }
50+
51+ public function score ($ thread )
52+ {
53+ $ trending = Cache::get ($ this ->cacheKey (), collect ());
54+
55+ if (! isset ($ trending [$ thread ->id ])) {
56+ return 0 ;
57+ }
58+
59+ return $ trending [$ thread ->id ]->score ;
4060 }
4161
4262 /**
43- * 重置所有热门线程.
63+ * 重置所有热门线程
4464 */
4565 public function reset ()
4666 {
47- Redis:: del ($ this ->cacheKey ());
67+ return Cache:: forget ($ this ->cacheKey ());
4868 }
4969}
0 commit comments