账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    swoole_event_add可以把Coroutine\Redis的subscribe也转为异步吗?
    67
    0

    问题描述

    redis的订阅是否能用swoole_event_add转为异步?网上能查到的大部分同步写法类似官网: https://wiki.swoole.com/wiki/page/1041.html

    相关代码

    我使用 swoole_event_add 没调通,求教:

    <?php
    $serv = new swoole_websocket_server('0.0.0.0', 9999, SWOOLE_PROCESS);
    $serv->on('message', function ($server, $request) {
    
    });
    
    $process = new \swoole_process(function (\swoole_process $process) {
        $process->name('publish process');
        swoole_timer_tick(2000, function ($timerId) {
            $redis = new \Swoole\Coroutine\Redis();
            $redis->connect('127.0.0.1', 6379);
            $res = $redis->publish('my_test', rand(1000, 9999));
            $redis->close();
        });
    }, false, 1, true);
    $serv->addProcess($process);
    
    $process = new \swoole_process(function (\swoole_process $process) {
        $process->name('subscribe process');
        $redis = new \Swoole\Coroutine\Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->subscribe(['my_test']);
        // 异步写法不正常
        swoole_event_add($redis->sock, function ($pipe) use ($redis) {
            $msg = $redis->recv();
            if (empty($msg)) {
                return;
            }
            list($type, $name, $info) = $msg;
            if ($type == 'message' && ! empty($info)) {
                var_dump('subscribe = ' . $info);
            }
        });
        /*
        // 同步写法正常
        do {
            $msg = $redis->recv();
            if (empty($msg)) {
                continue;
            }
            list($type, $name, $info) = $msg;
            if ($type == 'message' && ! empty($info)) {
                var_dump('subscribe = ' . $info);
            }
        } while (1);
        */
    }, false, 1, true);
    $serv->addProcess($process);
    
    $serv->start();

    你期待的结果是什么?实际看到的错误信息又是什么?

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    • 桃沢樱. 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部