【发布时间】:2016-03-17 01:25:24
【问题描述】:
我有 ~5-6k $items 需要在数据库中更新。每个项目都需要一个 HTTP 请求来从页面获取数据。在 HTTP GET 请求中,我得到了很大的数组(~500-2500),我只需要插入那些不在数据库中的行。我的流浪苏格兰威士忌盒上的当前脚本(每 2-4 分钟 1 个项目)似乎需要很长时间。
简化示例:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use GuzzleHttp\Client;
use App\Item;
use App\ItemHistory;
use Carbon\Carbon;
use DB;
class UpdateController extends Controller
{
public function getStart() {
// Don't cancel the script
ignore_user_abort(true);
set_time_limit(0);
$client = new Client();
$items = Item::where('updated_at', '<=', Carbon::now()->subDay())->get();
foreach($items as $item) {
$response = $client->request('GET', 'API_URL');
// get the body
$body = $response->getBody()->getContents();
$hugeArray = $body['history']; // can be from 100 to 5 000 lines and I use regex to get the "history" array from the body
$arrayCollection = collect($hugeArray);
foreach($arrayCollection->take(-100) as $row) { // I take the last 100 since each row = 1 hour, so I get items in the last 100 hours
$date = new \DateTime($row['created_at']);
if( ! ItemHistory::whereItemId($item->id)->whereSoldAt($date)->count()) { // Checking if it already exists
// I insert the new rows..
$history = new ItemHistory;
// ....
$history->save();
}
}
}
}
}
我实际上是抓取数据并使用正则表达式在正文响应中查找数组。
难道我做错了什么?它需要很长时间才能移动到下一个$item。
【问题讨论】:
-
您可以使用事务来加快查询速度并最大限度地减少对数据库的访问。 laravel.com/docs/5.1/database#database-transactions
-
此外,您进行的 HTTP 调用可能会比实际插入数据库更慢。