我有一些耗时的代码来处理一系列HTTP请求的结果,我想在后台运行这些请求。我正在使用Redis商店来管理队列。以下是我尝试过的:
Queue::push( 'FetchUrls', [
'urls' => [ 'http://one.com', 'http://two.com', 'http://three.com' ],
'complete' => function( $response ) { /* process data returned by URL here */ },
'error' => function( $error ) { /* process HTTP errors here */ },
]);Redis队列存储中显示的是$data参数的$data序列化:
{
"job": "FetchUrls",
"data": {
"urls": [
"http:\/\/one.com",
"http:\/\/two.com",
"http:\/\/three.com"
],
"complete": [],
"error": []
},
"id": "aAlkNM0ySLXcczlLYho19TlWYs9hStzl",
"attempts": 1
}如您所见,回调只是显示为队列存储中的空数组。我以前从未使用队列类,所以我可能以错误的方式处理这个问题。我想找个解决这个问题的最佳方法。谢谢!
发布于 2014-09-22 04:31:23
您可以传递函数名并使用类似于call_user_func()的内容调用它们。
Queue::push('FetchUrls', [
'urls' => ['http://one.com', 'http://two.com', 'http://three.com'],
'complete' => ['ResponseHandler', 'fetchComplete'],
'error' => ['ResponseHandler', 'fetchError'],
]);
class FetchUrls
{
public function fire($job, $data)
{
list($urls, $complete, $error) = $data;
foreach ($urls as $url) {
if ($response = $this->fetch($url)) {
$job->delete();
call_user_func($complete, $response);
} else {
$job->release();
call_user_func($error, $this->getError());
}
}
}
private function fetch($url)
{
// ...
}
private function getError()
{
// ...
}
}
class ResponseHandler
{
public static function fetchComplete($response)
{
// ...
}
public static function fetchError($error)
{
// ...
}
}这种方法有一个非基于类的版本,但这是相对干净的。
以call_user_func()为第一个参数的['ResponseHandler', 'fetchComplete']将调用ResponseHandler::fetchComplete()。
发布于 2014-09-21 22:00:08
为了安全起见,您应该只推送数组(因为序列化的问题)。
要回答您的问题-没有解决的办法,您应该重新考虑逻辑。
https://stackoverflow.com/questions/25963881
复制相似问题