Get the App
SLTechnology News&Howtos  ›  Database  › 

How to send subscription messages to WebSocket clients in Redis

Shulou Source: shulou.com Published: 2022-06-01 16:45:37 10月14日 Update

PHP's redis extension is a blocking IO, and when using the subscription / publish mode, it will cause the entire process to enter blocking. Therefore, it must be implemented using the Swoole\ Redis asynchronous client.

Instance code

$server = new swoole_websocket_server ("0.0.0.0", 9501); $server- > on ('workerStart', function ($server, $workerId) {$client = new swoole_redis; $client- > on (' message', function (swoole_redis $client, $result) use ($server) {if ($result [0] = = 'message') {foreach ($server- > connections as $fd) {$server- > push ($fd, $result [1]) }); $client- > connect ('127.0.0.1, 6379, function (swoole_redis $client, $result) {$client- > subscribe (' msg_0');}); $server- > on ('open', function ($server, $request) {}); $server- > on (' message', function (swoole_websocket_server $server, $frame) {$server- > push ($frame- > fd, "hello");}) $server- > on ('close', function ($serv, $fd) {}); $server- > start ()

Realization process

The Swoole\ Redis client is created when the process starts (onWorkerStart) to connect to the Redis server

After the connection is successful, subscribe to the msg_0 topic message

When there is a new message, Swoole\ Redis triggers the onMessage event callback

In this callback function, use $server- > connections to traverse all connections to the server and send messages

These are the details of forwarding subscription messages from Redis to WebSocket clients. For more information, please follow other related articles!

Tags: Clients messages subscriptions clients servers processes services blocking success topics events code content functions instances that is articles more patterns end Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL macOS Shulou Tech Info Redmi NVidia