php - symfony2 和 swiftmailer 的内存泄漏

标签 php symfony swiftmailer

我正在使用 symfony2 命令作为 cron 作业来向站点成员发送批量电子邮件。

实际代码:

$output->writeln('Before: '.(memory_get_usage() / 1024 / 1024));

$mailer->send($m);

$output->writeln('After: '.(memory_get_usage() / 1024 / 1024));

我的结果:

Before: 182.38 MB
After: 183.73 MB

每次我发送电子邮件时,swiftmailer 都会额外消耗 1+MB 的内存。这似乎不对,但每次发送新消息时内存都会增加。我在这里做错了什么吗?

最佳答案

SwiftMailer 内存假脱机系统

您指出的问题实际上与其说是问题,不如说是解决方案。您没有做错任何事情,这是由于 SwiftMailer 的内部假脱机发送电子邮件的方式。

send() 方法上,SwiftMailer 实际上并没有发送任何东西,而是简单地将它放入他的假脱机中。默认情况下,假脱机选项是 memory,假脱机刷新发生在内核终止之前。所以 memory_get_usage() 不可能告诉您内存已释放(因为很明显,您的脚本仍在运行并且 SwiftMailer 尚未刷新其假脱机)。

来自 Symfony2 文档:

When you use spooling to store the emails to memory, they will get sent right before the kernel terminates. This means the email only gets sent if the whole request got executed without any unhandled Exception or any errors.

使用文件假脱机系统

如果此假脱机选项给您带来麻烦,您可以切换到 File 假脱机选项。

可以通过改变这个来完成:

# app/config/config.yml
swiftmailer:
    # ...
    spool: { type: memory }

对此:

# app/config/config.yml
swiftmailer:
    # ...
    spool:
        type: file
        path: /path/to/spool

然后,您可以配置一个 cron 作业来自动定期刷新 spool:

$ php app/console swiftmailer:spool:send --env=prod

不使用线轴

或者,您可以选择完全不使用假脱机系统,这意味着您的所有电子邮件都将在脚本执行期间发送。它会让您摆脱内存问题,但可能会伤害您的用户,具体取决于您是否在他们请求页面时发送邮件。但是当您通过 cron 作业执行此操作时,在您的情况下肯定不会有问题。不过,可能有一天。

关于php - symfony2 和 swiftmailer 的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21617163/

相关文章:

php - NetBeans、PhpStorm...自定义 PHP 扩展的代码完成

php - 如何在 Yii 中使用事件

forms - Symfony 2 如何使用某些标准嵌入集合表单

php - yaml/symfony2 : Override configurations

symfony - 在 Symfony 中意外的标记 "operator"值 "="("end of print statement"预期)

php - Yii swiftmailer 无法在实时服务器上工作

laravel - 在 Laravel 4 中使用 SwiftMailer 发送邮件

php - 使用AJAX和PHP输出PDF

php - Swift Mailer 不返回 smtp 邮件失败

php - 包含类别和子类别的下拉菜单无法正常工作