• 如何实现从 Redis 中订阅消息转发到 WebSocket 客户端


    PHP 的redis扩展是阻塞式 IO ,使用订阅/发布模式时,会导致整个进程进入阻塞。因此必须使用SwooleRedis异步客户端来实现。

    实例代码

     1 $server = new swoole_websocket_server("0.0.0.0", 9501);
     2 
     3 $server->on('workerStart', function ($server, $workerId) {
     4     $client = new swoole_redis;
     5     $client->on('message', function (swoole_redis $client, $result) use ($server) {
     6         if ($result[0] == 'message') {
     7             foreach($server->connections as $fd) {
     8                 $server->push($fd, $result[1]);
     9             }
    10         }
    11     });
    12     $client->connect('127.0.0.1', 6379, function (swoole_redis $client, $result) {
    13         $client->subscribe('msg_0');
    14     });
    15 });
    16 
    17 $server->on('open', function ($server, $request) {
    18 
    19 });
    20 
    21 $server->on('message', function (swoole_websocket_server $server, $frame) {
    22     $server->push($frame->fd, "hello");
    23 });
    24 
    25 $server->on('close', function ($serv, $fd) {
    26 
    27 });
    28 
    29 $server->start();

    实现过程

    • 在进程启动(onWorkerStart)时创建了SwooleRedis客户端,连接到Redis服务器

    • 连接成功后,订阅msg_0主题的消息

    • 当有新的message时,SwooleRedis会触发onMessage事件回调

    • 在这个回调函数中使用$server->connections遍历服务器所有的连接,发送消息

  • 相关阅读:
    Kafka介绍
    测试Random类nextInt()方法连续两次结果一样的概率
    Java LinkedHashMap学习
    AES加密
    DES加密
    Windows访问VirtualBox的Redis服务器
    ubuntu配置JDK环境
    初学Python
    commons Collections4 MultiMap
    Guava bimap
  • 原文地址:https://www.cnblogs.com/luojianqun/p/7489915.html
Copyright © 2020-2023  润新知