请问下webman中怎么才能使用workerman/http-client

happy321

如果是使用自定义类 要怎么触发workerman/http-client来发送请求获取数据?

1461 2 2
2个回答

walkor

webman/http-client 目前不支持同步用法,用curl或者guzzle吧

  • happy321 2022-08-22

    请问curl或者guzzle 可以在webman中调用,发送异步请求吗? curl好像不支持吧?

  • chaz6chez 2022-08-22

    guzzle支持异步请求,在webman httpServer的OnMessage回调的业务逻辑上下文内是同步阻塞的,但可以并行发送多次请求;
    插件https://www.workerman.net/plugin/50中有webman/http-client及guzzle异步请求的相关使用案例代码;

    1. Guzzle的异步用法:https://github.com/workbunny/webman-nacos/blob/main/src/Process/ConfigListenerProcess.php 【82行-101行】
    2. Workerman/http-client:https://github.com/workbunny/webman-nacos/blob/main/src/Process/AsyncConfigListenerProcess.php 【78行-91行】
  • happy321 2022-08-22

    谢谢

  • happy321 2022-08-22

    "每个 worker 都可以在同请求建立链接后,请求传输数据期间 可以 不阻塞 的去处理其他请求" 请问等待curl返回结果的这段时间,这个worker会执行其他请求吗?

  • tanhongbin 2022-08-23

    每个worker进程都是同一时间只会处理一个请求

  • happy321 2022-08-23

    谢谢 我有点蒙了 之前好像看到 一个请求在读取数据库等待的时候 这个worker进程好像还会处理其他请求~~发送curl等待返回结果的时候,这个worker进程也会先处理其他请求吗?然后等这个curl有结果返回,再回来处理?还是curl只是在等待返回?

  • walkor 2022-08-23

    当前进程处理curl时,当前进程不会处理其它请求。

  • happy321 2022-08-23

    谢谢啦

  • talentstone 2022-08-26

    如果并发在2000 左右,用curl 会不会出现瓶颈 ?

  • chaz6chez 2022-08-26

    看业务

ontheway

是这样的:

  1. 首先,webman每个worker处理请求是阻塞的(一个请求处理完再处理下一个)
  2. guzzle支持异步请求,意思就是你可以在某个请求的处理程序中并发的发送请求

代码如下:

<?php
namespace App\api\controller;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise\Utils;
use Psr\Http\Message\ResponseInterface;

class Index
{
    public function index()
    {
        echo 'start: ' . time() . PHP_EOL;

        $client = new Client();
        $promises  = [];

        //异步请求一
        $promises[] = $client->getAsync('http://www.webman.com/test')
            ->then(
                function (ResponseInterface $res) {
                    echo 'res1: ' . $res->getBody() . ' ' . time() . PHP_EOL;
                },
                function (RequestException $e) {
                    echo $e->getMessage() . "\n";
                }
            );

        //异步请求二
        $promises[] = $client->getAsync('http://www.webman.com/test2')
            ->then(
                function (ResponseInterface $res) {
                    echo 'res2: ' . $res->getBody() . ' ' . time() . PHP_EOL;
                },
                function (RequestException $e) {
                    echo $e->getMessage() . "\n";
                }
            );

        //等待上面两个异步请求完成
        Utils::inspectAll($promises);

        return response('api index');
    }
}
  • talentstone 2022-08-26

    赞,多谢,学习下。

  • liziyu 2022-08-27

    谢谢,学习了!

  • evilk 2022-08-27

    我之前也这样用过,确实会提高响应时间,因为只会等待请求时间最长的那个请求
    但有一种特殊情况
    如果第二个请求,需要依赖第一个请求的结果,就不能这样发送并发请求
    这种并发请求,在适用于.每个请求之间,互不依赖的情况

年代过于久远,无法发表回答
🔝