dev*_*v02 9 php mysql memory-management laravel
我试图将postgres数据库中的数据插入到mysql数据库中.100000我需要导入大约记录.但是Iam总是出现内存问题.
Out of memory (allocated 1705508864) (tried to allocate 222764 bytes)
我使用Laravel 5来做这个,这里是代码:
// to avoid memory limit or time out issue
ini_set('memory_limit', '-1');
ini_set('max_input_time', '-1');
ini_set('max_execution_time', '0');
set_time_limit(0);
// this speeds up things a bit
DB::disableQueryLog();
$importableModels = [
// array of table names
];
$failedChunks = 0;
foreach ($importableModels as $postGresModel => $mysqlModel) {
$total = $postGresModel::count();
$chunkSize = getChunkSize($total);
// customize chunk size in case of certain tables to avoid too many place holders error
if ($postGresModel === 'ApplicationFormsPostgres') {
$chunkSize = 300;
}
$class = 'App\\Models\\' . $mysqlModel;
$object = new $class;
// trucate prev data //
Eloquent::unguard();
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
$object->truncate();
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
Eloquent::reguard();
$postGresModel::chunk($chunkSize, function ($chunk) use ($postGresModel, $mysqlModel, $failedChunks, $object) {
// make any adjustments
$fixedChunk = $chunk->map(function ($item, $key) use ($postGresModel) {
$appendableAttributes = $postGresModel::APPEND_FIELDS;
$attributes = $item->getAttributes();
// replace null/no values with empty string
foreach ($attributes as $key => $attribute) {
if ($attribute === null) {
$attributes[$key] = '';
}
}
// add customized attributes and values
foreach ($appendableAttributes as $appendField) {
if ($appendField === 'ssn') {
$value = $attributes['number'];
$attributes[$appendField] = substr($value, 0, 4);
} else {
$attributes[$appendField] = '';
}
}
return $attributes;
});
// insert chunk of data in db now
if (!$object->insert($fixedChunk->toArray())) {
$failedChunks++;
}
});
}
Run Code Online (Sandbox Code Playgroud)
80000在此之前插入行时会出现内存问题.
我怀疑map地图功能中的集合函数或循环有问题.我甚至尝试将内存设置和时间限制设置设置为无限制,但无济于事.可能是我需要使用引用变量或其他东西,但我不知道如何.
可以在上面的代码中进行任何优化以减少内存使用吗?
或者我如何通过代码有效地将大型数据从大型PostgreSQL数据库导入MySQL?
任何人都可以告诉我这里做错了什么或为什么整个内存消耗殆尽?
PS:我在本地开发机器上做这个,它有4GB内存(Windows 8).PHP版本:5.6.16
毫无疑问,你的某个地方出现了内存泄漏。我猜想在$chunk->map()或 之内的某个地方$object->insert($fixedChunk->toArray())。我们只能猜测,因为实现是隐藏的。
但是,我会尽可能使用生成器。该代码可能如下所示:
function getAllItems() {
$step = 2000;
for ($offset = 0 ;; $offset += $step) {
$q = "SELECT * FROM items_table LIMIT $offset, $step";
if (! $items = Db::fetchAll($q)) {
break;
}
foreach ($items as $i) {
yield $i;
}
}
}
foreach (getAllItems() as $item) {
import_item($item);
}
Run Code Online (Sandbox Code Playgroud)
我敢说,使用生成器,您几乎可以将任意数量的数据从一个数据库导入到另一个数据库。
| 归档时间: |
|
| 查看次数: |
1617 次 |
| 最近记录: |