@@ -11,12 +11,14 @@ class Redis
1111 public Client $ client ;
1212 private string $ type ;
1313 private int $ score ;
14+ private string $ hashKey ;
1415 private int $ expire ;
1516
1617 public function __construct (array $ config = [])
1718 {
1819 $ this ->type = 'string ' ;
1920 $ this ->score = 0 ;
21+ $ this ->hashKey = '' ;
2022 $ this ->expire = -1 ;
2123
2224 $ options = [
@@ -67,6 +69,18 @@ public function score(int $score): static
6769 return $ this ;
6870 }
6971
72+ /**
73+ * 设置hash的key
74+ *
75+ * @return $this
76+ */
77+ public function hashKey (string $ key ): static
78+ {
79+ $ this ->hashKey = $ key ;
80+
81+ return $ this ;
82+ }
83+
7084 /**
7185 * 设置过期时间.
7286 *
@@ -97,19 +111,34 @@ public function remember(string $key, callable $callback): mixed
97111 'get ' => function () use ($ key , $ callback ) {
98112 $ zset = $ this ->client ->zrangebyscore ($ key , $ this ->score , $ this ->score );
99113 if (is_array ($ zset ) && count ($ zset ) === 1 ) {
100- return json_decode ( current ($ zset), true );
114+ return current ($ zset );
101115 }
102116
103117 // 没有匹配写入cache
104118 $ return = $ callback ();
105- $ this ->client ->zadd ($ key , $ this ->score , json_encode ($ return ));
106-
119+ $ this ->client ->zadd ($ key , $ this ->score , $ return );
107120 return $ return ;
108121 },
109122 'put ' => function ($ value ) use ($ key ): void {
110- $ this ->client ->zadd ($ key , $ this ->score , json_encode ( $ value) );
123+ $ this ->client ->zadd ($ key , $ this ->score , $ value );
111124 },
112125 ],
126+ 'hash ' => [
127+ 'get ' => function () use ($ callback , $ key ) {
128+ $ hash = $ this ->client ->hget ($ key , $ this ->hashKey );
129+ if ($ hash ) {
130+ return $ hash ;
131+ }
132+
133+ // 没有匹配写入cache
134+ $ return = $ callback ();
135+ $ this ->client ->hset ($ key , $ this ->hashKey , $ return );
136+ return $ return ;
137+ },
138+ 'put ' => function ($ value ) use ($ key ) {
139+ $ this ->client ->hset ($ key , $ this ->hashKey , $ value );
140+ }
141+ ]
113142 ];
114143
115144 $ getType = (string ) $ this ->client ->type ($ key );
0 commit comments