Home > Database > Redis > body text

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

藏色散人
Release: 2020-06-13 16:08:22
forward
2843 people have browsed it

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();
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!