@@ -175,6 +175,36 @@ public function unsubscribe($appId, string $channel): bool
175175 return true ;
176176 }
177177
178+ /**
179+ * Subscribe to the app's pubsub keyspace.
180+ *
181+ * @param mixed $appId
182+ * @return bool
183+ */
184+ public function subscribeToApp ($ appId ): bool
185+ {
186+ $ this ->subscribeClient ->__call ('subscribe ' , [$ this ->getTopicName ($ appId )]);
187+
188+ $ this ->publishClient ->__call ('hincrby ' , [$ this ->getTopicName ($ appId ), 'connections ' , 1 ]);
189+
190+ return true ;
191+ }
192+
193+ /**
194+ * Unsubscribe from the app's pubsub keyspace.
195+ *
196+ * @param mixed $appId
197+ * @return bool
198+ */
199+ public function unsubscribeFromApp ($ appId ): bool
200+ {
201+ $ this ->subscribeClient ->__call ('unsubscribe ' , [$ this ->getTopicName ($ appId )]);
202+
203+ $ this ->publishClient ->__call ('hincrby ' , [$ this ->getTopicName ($ appId ), 'connections ' , -1 ]);
204+
205+ return true ;
206+ }
207+
178208 /**
179209 * Add a member to a channel. To be called when they have
180210 * subscribed to the channel.
@@ -258,6 +288,17 @@ public function channelMemberCounts($appId, array $channelNames): PromiseInterfa
258288 });
259289 }
260290
291+ /**
292+ * Get the amount of connections aggregated on multiple instances.
293+ *
294+ * @param mixed $appId
295+ * @return null|int|\React\Promise\PromiseInterface
296+ */
297+ public function getGlobalConnectionsCount ($ appId )
298+ {
299+ return $ this ->publishClient ->hget ($ this ->getTopicName ($ appId ), 'connections ' );
300+ }
301+
261302 /**
262303 * Handle a message received from Redis on a specific channel.
263304 *
@@ -321,8 +362,8 @@ public function onMessage(string $redisChannel, string $payload)
321362 */
322363 protected function getConnectionUri ()
323364 {
324- $ name = config ('websockets.replication.redis.connection ' ) ?: 'default ' ;
325- $ config = config (' database.redis ' )[ $ name] ;
365+ $ name = config ('websockets.replication.redis.connection ' , 'default ' ) ;
366+ $ config = config (" database.redis. { $ name}" ) ;
326367
327368 $ host = $ config ['host ' ];
328369 $ port = $ config ['port ' ] ?: 6379 ;
@@ -377,13 +418,19 @@ public function getServerId()
377418 * app ID and channel name.
378419 *
379420 * @param mixed $appId
380- * @param string $channel
421+ * @param string|null $channel
381422 * @return string
382423 */
383- protected function getTopicName ($ appId , string $ channel ): string
424+ protected function getTopicName ($ appId , string $ channel = null ): string
384425 {
385426 $ prefix = config ('database.redis.options.prefix ' , null );
386427
387- return "{$ prefix }{$ appId }: {$ channel }" ;
428+ $ hash = "{$ prefix }{$ appId }" ;
429+
430+ if ($ channel ) {
431+ $ hash .= ": {$ channel }" ;
432+ }
433+
434+ return $ hash ;
388435 }
389436}
0 commit comments