Flo*_*ove 3 php queue redis laravel
我在一个应用程序中遇到了问题,我在后端进行了很多 api 调用。因此,应用程序收到超时错误。
有人建议我应该使用队列。我试图用 redis 这样做。该函数进入工作并使用处理程序,但我希望页面加载我给它的数据,而没有来自 api 的数据,而 api 调用正在后台进行。相反,它就像我没有使用队列时一样。我试图按照教程来做到这一点,但他们做的并不完全一样,我无法调整它所以它对我有用。
有关我在工作中做什么的信息。我得到了一个 csv 的评论,我使用评论中的数字来调用 api,我得到了一个 8-10 个字段的 json。我需要调用 api 大约 650 次,所以当我想将数据保存到数据库时需要很长时间。我一次使用一个插入来使用“缓存”,所以我不会两次执行相同的调用。
这是我调用工作的控制器。
class ImportController extends Controller
{
public function checkErrors(Request $request)
{
$this->checkAgainstDocuments($csv_id);
$supplierErrorIds=$this->checkSupplierErrors($parameters, $company , $csv_id);
$timesheetErrors=TsData::whereIn('id', $supplierErrorIds)->sortable()->paginate(20);
return view('show_errors', compact('timesheetErrors', 'company', 'csv_id'));
}
public function checkAgainstDocuments($csv_id)
{
GetFromDocumentsAPI::dispatch($csv_id)->delay(now()->addMinutes(10));
}
}
Run Code Online (Sandbox Code Playgroud)
这是我使用的工作:
class GetFromDocumentsAPI implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $csv_id;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($csv_id)
{
//
$this->csv_id=$csv_id;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$comments = TsData::select('id', 'comments')->where('csv_id', $this->csv_id)->get()->toArray();
$commentIDs = array();
foreach ($comments as $comment) {
preg_match_all('/(\d{5,})/', $comment['comments'], $out, PREG_PATTERN_ORDER);
foreach ($out as $item) {
$commentIDs[$comment['id']] = $item;
}
}
$commentIDs = array_filter($commentIDs);
$apiKey=config('app.apiKey');
$documentsResponse = array();
Issue::truncate();
$arrayTest=[];
foreach ($commentIDs as $key => $commentID) {
foreach ($commentID as $item) {
$issue = Issue::where('id', $item)->first();
if ($issue === null) {
try {
$url = file_get_contents('https://documents.calibrate.be/issues/' . $item . '.json?key=' . $apiKey);
$json = json_decode($url, true);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$issue = Issue::Create(['id'=>$item, 'name'=>$json['issue']['subject'], 'projectId'=>$json['issue']['project']['id'], 'priority'=>$json['issue']['priority']['id']]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
配置/队列.php
'default' => env('QUEUE_DRIVER', 'redis'),
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
Run Code Online (Sandbox Code Playgroud)
默认情况下,Laravel 使用sync驱动程序来处理队列。
确保将QUEUE_CONNECTIONconfig 变量设置为database或redis或任何其他服务。同样可以在.env文件中设置,也可以在文件中设置config/queue.php。
要使用database,请执行
php artisan queue:table和php artisan migrate。这将创建所有需要运行的表。php artisan queue:work要使用redis,请执行
sudo apt-get install redis-server并启动 redis 服务器$ sudo systemctl enable redis-server.service。(对于基于 Linux 的系统).envor 中配置和设置 redis 特定变量config/queue.phpPSphp artisan config:clear进行更改后运行命令,以便更改反映在缓存中。