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();

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

andy 2
11月20日提问
0 个回答

撰写答案

推广链接