php swoole hyperf,关于php:Hyperf为什么要关闭Swoole协程短名称

在Hyperf官网文档的服务器要求中提到

Swoole PHP 扩大 >= 4.5,并敞开了 Short Name

并且,在文档的常见问题中也会看到Swoole 短名未敞开这一个tag。

我想问了,那为什么hyperf肯定要敞开掉Swoole的协程短名称呢

首先,咱们先看一下什么是Swoole的协程短名称

所有的 Swoole\Coroutine 前缀的类名映射为 Co。此外还有上面的一些映射:创立协程 go() 函数,通道操作 chan() 函数,提早执行 defer() 函数

从下面的解释咱们晓得了,hyperf次要就是不想让咱们应用以上这几个函数,然而为啥不让咱们应用的呢?想到之前在代码中常常应用go()函数来解决代码中的阻塞问题,难道说我写的代码并没有协程化?在Hyperf通过测试之后发现,go()函数协程话的确是失效的,那到底是什么让原本曾经被禁用的go()函数又“复活”了呢?

在phpStrom只点击go()函数咱们跳转到了vendor/hyperf/utils/src/Functions.php文件,该文件是在composer.json中指定的自动化加载文件

if (! function_exists('go')) {

/**

* @return bool|int

*/

function go(callable $callable)

{

$id = Coroutine::create($callable);

return $id > 0 ? $id : false;

}

}

如果框架里没定义go()函数的话,就会执行这里的逻辑去调用Coroutine::create($callable),留神这里的Coroutine类并不是Swoole\Coroutine,而是vendor/hyperf/utils/src/Coroutine.php

public static function create(callable $callable): int

{

$result = SwooleCoroutine::create(function () use ($callable) {

try {

call($callable);

} catch (Throwable $throwable) {

if (ApplicationContext::hasContainer()) {

$container = ApplicationContext::getContainer();

if ($container->has(StdoutLoggerInterface::class)) {

/* @var LoggerInterface $logger */

$logger = $container->get(StdoutLoggerInterface::class);

/* @var FormatterInterface $formatter */

if ($container->has(FormatterInterface::class)) {

$formatter = $container->get(FormatterInterface::class);

$logger->warning($formatter->format($throwable));

} else {

$logger->warning(sprintf('Uncaptured exception[%s] detected in %s::%d.', get_class($throwable), $throwable->getFile(), $throwable->getLine()));

}

}

}

}

});

return is_int($result) ? $result : -1;

}

能够看到,咱们“劫持”了go()函数,给他做了一些改变,捕捉了创立协程时抛出的异样,将异样打印到管制台上。(注:对于Coroutine::create形式创立的协程在callable中存在异样时会抛出Fatal error,这是咱们不违心看到的)。

所以,到这里咱们仿佛了解了为什么Hyperf要敞开Swoole的短名称,目标就是劫持go()、co()函数来捕捉callable的异样防止过程抛出Fatal error

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值