Home  >  Article  >  Database  >  Implement subscription messages from Redis and forward them to the WebSocket client

Implement subscription messages from Redis and forward them to the WebSocket client

藏色散人
藏色散人forward
2020-06-13 16:08:222852browse

Implement subscription messages from Redis and forward them to the WebSocket client

PHP's redis extension is blocking IO. When using the subscription/publishing mode, the entire process will be blocked. Therefore, it must be implemented using 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();

Implementation process

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

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

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

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

Related recommendations: "redis tutorial"

The above is the detailed content of Implement subscription messages from Redis and forward them to the WebSocket client. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete