从 Laravel Jobs 返回数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37333691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return data from Laravel Jobs
提问by Bushikot
I am developing API on Laravel for mobile application.
我正在 Laravel 上为移动应用程序开发 API。
Methods will make requests to other API's, combine and filter data, changing it's structure etc.
方法将向其他 API 发出请求、组合和过滤数据、更改其结构等。
One of the requirements to app is to respond no more than 30 seconds, or not respond at all. So, I have to repeat requests as much as I have time. I trying to realize that with Laravel Queues, and currently have something like that in my Job class:
对应用程序的要求之一是响应不超过 30 秒,或者根本不响应。所以,我必须尽可能多地重复请求。我试图通过 Laravel 队列来实现这一点,并且目前在我的 Job 类中有类似的东西:
private $apiActionName;
public function __construct($apiActionName)
{
$this->apiActionName = $apiActionName;
}
public function handle(SomeService $someService)
{
return $someService->{$this->apiActionName}();
}
And this action code in controller:
控制器中的这个动作代码:
public function someAction()
{
$data = $this->dispatch(new MyJob($apiActionName));
return response()->json($data);
}
Yes, I know it is bad idea to return value from job, but expect that it's possible. However $this->dispatch()returns only queued job ID, not result of handlemethod.
是的,我知道从工作中返回价值是个坏主意,但希望这是可能的。但是$this->dispatch()只返回排队的作业 ID,而不是handle方法的结果。
TL;DR:How can I return data from queued Job, without saving it anywhere, and even if it have more than one tries in the queue? Maybe somebody know other ways if Jobs are not suitable for this. Any advice will be appreciated.
TL;DR:如何从排队的作业返回数据,而不将其保存在任何地方,即使它在队列中进行了多次尝试?如果乔布斯不适合这个,也许有人知道其他方法。任何建议将被认真考虑。
Thanks in advance!
提前致谢!
回答by Denis Mysenko
You are returning data in your Job class, but assigning $data to a dispatcher - note that dispatch() method is not a part of your Job class.
您正在 Job 类中返回数据,但将 $data 分配给调度程序 - 请注意, dispatch() 方法不是 Job 类的一部分。
You could try something like this, assuming that your jobs run synchronously:
假设您的作业同步运行,您可以尝试这样的操作:
private $apiActionName;
private $response;
public function __construct($apiActionName)
{
$this->apiActionName = $apiActionName;
}
public function handle(SomeService $someService)
{
$this->response = $someService->{$this->apiActionName}();
}
public function getResponse()
{
return $this->response;
}
And then in your controller:
然后在您的控制器中:
public function someAction()
{
$job = new MyJob($apiActionName);
$data = $this->dispatch($job);
return response()->json($job->getResponse());
}
Obviously, this won't work once you move to async mode and queues - response won't be there yet by the time you call getResponse(). But that's the whole purpose of async jobs :)
显然,一旦您进入异步模式和队列,这将不起作用——当您调用 getResponse() 时,响应还没有出现。但这就是异步作业的全部目的:)