簡體   English   中英

Cakephp-導入1萬行電子郵件地址

[英]Cakephp - import 10k lines of email adresses

我有一個腳本,該腳本讀取txt文件的大約1萬行,每行中都有一個電子郵件地址。 對於每個地址,我都會檢查其地址是否已被使用;如果是,我會將地址放入error數組中;如果不是,則將地址放入save數組中。

在foreach之后,如果錯誤數組中沒有地址,則執行$this->Newsletter->saveMany($data)

由於某些原因,當我導入大約500行以上時,總是會超時。 有沒有一種方法可以走另一種/更好的方法來避免超時?

請指教!

public function import() {
        $filename = './files/newsletterImport/newsletter.txt';

            $lines = file($filename);
            foreach ($lines as $line_num => $line) {

                // check unique
                if($email = $this->Newsletter->find('first', array('conditions' => array('email' => trim($line))))){
                    $error[$line_num]['email'] = trim($line);
                    $error[$line_num]['cancel'] = date('d.m.Y H:i:s', strtotime($email['Newsletter']['cancel']));
                }else{
                    $data[$line_num]['Newsletter']['email'] = trim($line);
                    $data[$line_num]['Newsletter']['active'] = 1;
                }

            }
            if(!$error){
                $this->Newsletter->create();
                if($this->Newsletter->saveMany($data)){
                    $this->set('msg', 'Success');
                }else{
                    $this->set('msg', 'Error! Nothing imported!');
                }
            }else{
                $this->set('msg', 'Error! Nothing imported!');
                $this->set('error', $error);
            }
        }else{
            $this->set('msg', 'No file found!');
        }

由於您實際上不知道什么時候超時,因此提供了一些提示。

1)量度每一段代碼的時間,除非您知道大部分時間都在占用什么部分。

2)您對數據庫的每一行都執行一次查詢,這相當於價值10k的查詢...我的心痛。 因此,考慮進行一個大查詢以獲取所有電子郵件,並將它們與php進行比較以了解它們是否唯一。 再說一次,也許SQL選項變得更有效(取決於您如何在PHP數組上進行搜索)

3)嘗試調整保存的選項 默認情況下,atomic選項為true,對於保存10k來說可能有點太多。

$this->Newsletter->saveMany($data, array('atomic'=>false));

如果那不能解決問題,請嘗試將數組划分並按階段保存。 我知道這很痛苦,但也許交易太多了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM