dispatch_func

设置dispatch函数,swoole底层了内置了5dispatch_mode,如果仍然无法满足需求。可以使用编写C++函数或PHP函数,实现dispatch逻辑。使用方法:

$serv->set(array(
	'dispatch_func' => 'my_dispatch_function',
));

dispatch_func1.9.7或更高版本可用
dispatch_func1.9.18或更高版本可以设置为PHP函数
dispatch_func仅在SWOOLE_PROCESS模式下有效,UDP/TCP/UnixSocket均有效

编写PHP函数

由于ZendVM无法支持多线程环境,即使设置了多个Reactor线程,同一时间只能执行一个dispatch_func。因此底层在执行此PHP函数时会进行加锁操作,可能会存在锁的争抢问题。请勿在dispatch_func中执行任何阻塞操作,否则会导致Reactor线程组停止工作。

$serv->set(array(
	'dispatch_func' => function ($serv, $fd, $type, $data) {
        var_dump($fd, $type, $data);
        return intval($data[0]);
    },
));

编写C++函数

在其他PHP扩展中,使用swoole_add_function注册长度函数到Swoole引擎中。

C++函数调用时底层不会加锁,需要调用方自行保证线程安全性

int dispatch_function(swServer *serv, swConnection *conn, swEventData *data);

int dispatch_function(swServer *serv, swConnection *conn, swEventData *data)
{
    printf("cpp, type=%d, size=%d\n", data->info.type, data->info.len);
    return data->info.len % serv->worker_num;
}

int register_dispatch_function(swModule *module)
{
    swoole_add_function("my_dispatch_function", (void *) dispatch_function);
}