【问题标题】:Guzzle Pool in Symfony 2 - Dealing with futureSymfony 2 中的 Guzzle Pool - 处理未来
【发布时间】:2016-07-22 23:42:46
【问题描述】:

我正在尝试在 Symfony 2 应用程序中使用 Guzzle 池。我正在考虑使用它,因为它能够一次发送并发请求。

但是,由于它本质上是异步的,我不确定如何在 Symfony 2 中将其用作服务。因为返回并不总是立即的。

例如,假设我在 Symfony 中有一个名为 Foo 的服务,它有类似这样的方法。

function test() 
{ 
    $request = $client->createRequest('GET', 'http://lt/?n=0', ['future' => true]);

    $client->send($request)->then(function ($response) {

        return "\n".$response->getBody();
    });

}

现在我像这样调用这个服务。

$service = $this->get('foo');
$result = $service->test();
echo $result;// does not work :( echoes out null

有什么办法可以解决这个问题。我真的很想使用 Future,因为我需要异步功能。

【问题讨论】:

  • $responsegetBody() 方法吗?你试过var_dump()你的$response吗?
  • 是的,我试过了,但这没有任何好处。由于那时响应还没有准备好。
  • 我的意思是在return "\n".$response->getBody();之前var_dump()
  • 响应很好,这不是问题,问题是如何处理 Symfony 中的 React Promise,我认为 Guzzle 在后台使用了它。

标签: symfony future guzzle


【解决方案1】:

您必须在应用程序中处理承诺(期货)或等待结果。

关于你的例子:首先,你没有从test() 返回任何东西;)因此你没有得到任何$result。正如我之前所说,您必须在两种不同的方式之间进行选择:1)在 test() 方法中等待 HTTP 调用并返回结果本身,或者 2)立即返回 Promise 并在您的应用程序中处理它(通过 then() , otherwise()wait() 最后)。

如果您为整个应用选择异步方式,代码可能如下所示:

function test() 
{ 
    return $client->getAsync('http://lt/?n=0')
        ->then(function ($response) {
            return "\n".$response->getBody();
        });
}

后来:

$service = $this->get('foo');
$promise = $service->test()->then(function ($responseString) {
    echo $responseString;
});

$promise->wait(); // Here you get the output.

我略微更改了 Guzzle 6 的代码(应在新项目中使用的当前版本的 Guzzle)。

顺便说一句,Guzzle 使用 its own implementation of promises,这与 React 无关。

【讨论】:

    猜你喜欢
    • 2020-06-21
    • 2017-08-02
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    相关资源
    最近更新 更多