我使用 Laravel Excel "maatwebsite/excel": "^3.1",
仅导入 400 条记录,其中包含 10 个字段。仅读取这些记录的过程需要大约 2GB 的 RAM(仅用于将数据读入集合),每次以 20 行的块读取它们(我尝试将块大小增加到 50,但它消耗了更多的 RAM)
try {
$collection = Excel::toCollection(
new UsersImport(
$entity,$user,$unique_fields,$update_duplicates,new JobHistory,$this->userTypeRepository,),storage_path().'/uploads/' . $usersFileName
);
} catch (\Throwable $th) {
throw new Exception($th);
}
UsersImport.php
class UsersImport implements ToCollection,WithHeadingRow,WithChunkReading,ShouldQueue,WithEvents
{
private $entity,$updateDuplicates,$uniqueFields,$jobHistory,$userTypeRepository;
use RemembersChunkOffset;
public function __construct(Entity $entity,User $user,array $uniqueFields,string $updateDuplicates,JobHistory $jobHistory,UserTypeRepository $userTypeRepository)
{
$this->entity = $entity;
$this->user = $user;
$this->updateDuplicates = $updateDuplicates;
$this->uniqueFields = $uniqueFields;
$this->jobHistory = $jobHistory;
$this->userTypeRepository = $userTypeRepository;
}
public function collection(Collection $rows) {
/* foreach ($rows as $row) {
$data = $row->toArray();
array_walk($data,array($this,'parseData'));
} */
}
public function chunkSize(): int
{
return 20;
}
public function registerEvents(): array
{
return [];
}
public function headingRow(): int
{
return 15;
}
}
为什么会发生这种情况以及如何使其消耗更少的 RAM?如果我尝试导入 800 个用户,我将需要 4GB RAM 才能使其工作!!