2
2
3
3
namespace App ;
4
4
5
- use Illuminate \Support \Facades \Redis ;
5
+ use Illuminate \Support \Facades \Cache ;
6
6
7
7
class Trending
8
8
{
@@ -13,7 +13,10 @@ class Trending
13
13
*/
14
14
public function get ()
15
15
{
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 ();
17
20
}
18
21
19
22
/**
@@ -31,19 +34,35 @@ private function cacheKey()
31
34
*
32
35
* @param Thread $thread
33
36
*/
34
- public function push ($ thread )
37
+ public function push ($ thread, $ increment = 1 )
35
38
{
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 ,
37
43
'title ' => $ thread ->title ,
38
44
'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 ;
40
59
}
41
60
42
61
/**
43
62
* 重置所有热门线程.
44
63
*/
45
64
public function reset ()
46
65
{
47
- Redis:: del ($ this ->cacheKey ());
66
+ return Cache:: forget ($ this ->cacheKey ());
48
67
}
49
68
}
0 commit comments