从 Laravel Jobs 返回数据 [英] Return data from Laravel Jobs

查看:47
本文介绍了从 Laravel Jobs 返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Laravel 上为移动应用开发 API.

I am developing API on Laravel for mobile application.

方法将向其他 API 发出请求、组合和过滤数据、改变其结构等.

Methods will make requests to other API's, combine and filter data, changing it's structure etc.

应用的要求之一是响应时间不超过 30 秒,或者根本不响应.所以,我必须尽可能多地重复请求.我试图通过 Laravel 队列实现这一点,并且目前在我的作业类中有类似的东西:

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:

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);
}

是的,我知道从工作中返回值是个坏主意,但希望这是可能的.但是 $this->dispatch() 只返回排队的作业 ID,而不是 handle 方法的结果.

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 handle method.

TL;DR: 如何从排队的作业返回数据,而不将其保存在任何地方,即使它在队列中进行了多次尝试?如果乔布斯不适合这个,也许有人知道其他方法.任何建议将不胜感激.

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.

提前致谢!

推荐答案

您正在 Job 类中返回数据,但将 $data 分配给调度程序 - 请注意 dispatch() 方法不是您的 Job 类的一部分.

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.

假设您的作业同步运行,您可以尝试这样的操作:

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;
}

然后在您的控制器中:

public function someAction()
{ 
    $job = new MyJob($apiActionName);
    $data = $this->dispatch($job);
    return response()->json($job->getResponse());
}

显然,一旦您进入异步模式和队列,这将不起作用 - 在您调用 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 :)

这篇关于从 Laravel Jobs 返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆