1818use Hyperf \Pool \Pool ;
1919use Psr \Container \ContainerInterface ;
2020
21+ /**
22+ * @method select(int $db)
23+ */
2124class RedisConnection extends BaseConnection implements ConnectionInterface
2225{
2326 /**
@@ -32,9 +35,13 @@ class RedisConnection extends BaseConnection implements ConnectionInterface
3235 'host ' => 'localhost ' ,
3336 'port ' => 6379 ,
3437 'auth ' => null ,
35- 'cluster ' => false ,
3638 'db ' => 0 ,
3739 'timeout ' => 0.0 ,
40+ 'cluster ' => [
41+ 'enable ' => false ,
42+ 'name ' => null ,
43+ 'seeds ' => [],
44+ ],
3845 'options ' => [],
3946 ];
4047
@@ -75,24 +82,18 @@ public function reconnect(): bool
7582 $ host = $ this ->config ['host ' ];
7683 $ port = $ this ->config ['port ' ];
7784 $ auth = $ this ->config ['auth ' ];
78- $ cluster = $ this ->config ['cluster ' ];
7985 $ db = $ this ->config ['db ' ];
8086 $ timeout = $ this ->config ['timeout ' ];
87+ $ cluster = $ this ->config ['cluster ' ]['enable ' ] ?? false ;
8188
8289 $ redis = null ;
8390 if ($ cluster !== true ) {
84- // Normal Redis (Non-cluster)
8591 $ redis = new \Redis ();
8692 if (! $ redis ->connect ($ host , $ port , $ timeout )) {
8793 throw new ConnectionException ('Connection reconnect failed. ' );
8894 }
8995 } else {
90- // Redis Cluster
91- try {
92- $ redis = new \RedisCluster (null , [$ host . ': ' . $ port ], $ timeout );
93- } catch (\Throwable $ e ) {
94- throw new ConnectionException ('Connection reconnect failed. ' . $ e ->getMessage ());
95- }
96+ $ redis = $ this ->createRedisCluster ();
9697 }
9798
9899 $ options = $ this ->config ['options ' ] ?? [];
@@ -138,4 +139,19 @@ public function setDatabase(?int $database): void
138139 {
139140 $ this ->database = $ database ;
140141 }
142+
143+ protected function createRedisCluster ()
144+ {
145+ try {
146+ $ seeds = $ this ->config ['cluster ' ]['seeds ' ] ?? [];
147+ $ name = $ this ->config ['cluster ' ]['name ' ] ?? null ;
148+ $ timeout = $ this ->config ['timeout ' ] ?? null ;
149+
150+ $ redis = new \RedisCluster ($ name , $ seeds , $ timeout );
151+ } catch (\Throwable $ e ) {
152+ throw new ConnectionException ('Connection reconnect failed. ' . $ e ->getMessage ());
153+ }
154+
155+ return $ redis ;
156+ }
141157}
0 commit comments