搜索
首页php框架LaravelLaravel 队列发送邮件

Laravel 队列发送邮件

Oct 21, 2019 pm 01:36 PM
laravel

批量处理任务的场景在我们开发中是经常使用的,比如邮件群发,消息通知,短信,秒杀等等,我们需要将这个耗时的操作放在队列中来处理,从而大幅度缩短Web请求和相应的时间。

下面讲解下Laravel中队列的使用

配置文件 config/queue.php

<?php
return [
    &#39;default&#39; => env(&#39;QUEUE_DRIVER&#39;, &#39;sync&#39;),
    &#39;connections&#39; => [
        &#39;sync&#39; => [
            &#39;driver&#39; => &#39;sync&#39;,
        ],
        &#39;database&#39; => [
            &#39;driver&#39; => &#39;database&#39;,
            &#39;table&#39; => &#39;jobs&#39;,
            &#39;queue&#39; => &#39;default&#39;,
            &#39;retry_after&#39; => 90,
        ],
        &#39;beanstalkd&#39; => [
            &#39;driver&#39; => &#39;beanstalkd&#39;,
            &#39;host&#39; => &#39;localhost&#39;,
            &#39;queue&#39; => &#39;default&#39;,
            &#39;retry_after&#39; => 90,
        ],
        &#39;sqs&#39; => [
            &#39;driver&#39; => &#39;sqs&#39;,
            &#39;key&#39; => &#39;your-public-key&#39;,
            &#39;secret&#39; => &#39;your-secret-key&#39;,
            &#39;prefix&#39; => &#39;https://sqs.us-east-1.amazonaws.com/your-account-id&#39;,
            &#39;queue&#39; => &#39;your-queue-name&#39;,
            &#39;region&#39; => &#39;us-east-1&#39;,
        ],
        &#39;redis&#39; => [
            &#39;driver&#39; => &#39;redis&#39;,
            &#39;connection&#39; => &#39;default&#39;,
            &#39;queue&#39; => &#39;default&#39;,
            &#39;retry_after&#39; => 90,
        ],
    ],
    &#39;failed&#39; => [
        &#39;database&#39; => env(&#39;DB_CONNECTION&#39;, &#39;mysql&#39;),
        &#39;table&#39; => &#39;failed_jobs&#39;,
    ],
];

配置文件默认使用的是同步驱动sync,每一种队列驱动的配置都可以在该文件中找到, 包括数据库, Beanstalkd, Amazon SQS, Redis。 其中还包含了一个null队列驱动用于那些放弃队列的任务。failed配置项用于配置失败队列任务存放的数据库及数据表。 

接下来我们需要创建一个队列任务类。

创建队列任务类,之后会在app/Jobs目录下生成一个SendEmail.php的文件

php artisan make:job SendEmail
<?php
namespace App\Jobs;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;
class SendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $user;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }
    /**
     * 执行队列的方法 比如发送邮件
     *
     * @return void
     */
    public function handle()
    {
      $user = $this->user;
      
      Mail::raw(&#39;这里填写邮件的内容&#39;,function ($message){
             // 发件人(你自己的邮箱和名称)
            $message->from(&#39;your_email@163.com&#39;, &#39;yourname&#39;);
            // 收件人的邮箱地址
            $message->to($this->user);
            // 邮件主题
            $message->subject(&#39;队列发送邮件&#39;);
        });
    }
}

任务类创建完之后到控制器 把数据加入到队列

创建发送消息的控制器 使用dispatch方法手动分发任务,方法里传一个任务类的实例

<?php
namespace App\Http\Controllers;
use App\Jobs\SendEmail;
use App\User;
class MessageController extends Controller
{
    public function index()
    {
        $user = User::find(1);
        $this->dispatch(new SendEmail($user));
    }
}

然后访问浏览器,运行项目把任务推送到队列中。然后使用Artisan命令,执行队列里的任务

php artisan queue:

● queue:work 默认只执行一次队列请求, 当请求执行完成后就终止;

● queue:listen 监听队列请求,只要运行着,就能一直接受请求,除非手动终止;

● queue:work --daemon同listen一样,不同的是work不需要再次加载框架,直接运行任务,一般推荐使用这个来处理队列监听。

● 注:使用 queue:work --daemon ,当更新代码的时候,需要停止,然后重新启动,这样才能把修改的代码应用上。

更多Laravel相关技术文章,请访问Laravel框架入门教程栏目进行学习!

以上是Laravel 队列发送邮件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:segmentfault。如有侵权,请联系admin@php.cn删除
如何使用Laravel迁移:逐步教程如何使用Laravel迁移:逐步教程May 13, 2025 am 12:15 AM

laravelmigrationsStreamLinedAtabasemangementbyallowingbolAlyChemachangeStobEdeDinedInphpcode,whobeversion-controllolleDandShared.here'showtousethem:1)createMigrationClassestodeFinePerationFineFineOperationsLikeCreatingingModifyingTables.2)

查找最新的Laravel版本:快速简便的指南查找最新的Laravel版本:快速简便的指南May 13, 2025 am 12:13 AM

要查找最新版本的Laravel,可以访问官方网站laravel.com并点击右上角的"Docs"按钮,或使用Composer命令"composershowlaravel/framework|grepversions"。保持更新有助于提升项目安全性和性能,但需考虑对现有项目的影响。

使用Laravel的更新:使用最新版本的好处使用Laravel的更新:使用最新版本的好处May 13, 2025 am 12:08 AM

youshouldupdateTotheLateStlaravelVerverSionForPerformanceImprovements,增强的安全性,newfeatures,BetterCommunitySupport,and long-term-Maintenance.1)绩效:Laravel9'Selover9'seloquentormoptimizatizationenenhanceApplicationsPeed.2)secuse:laravel8InIntrododeDodecter.2)

Laravel:我搞砸了我的迁移,我该怎么办?Laravel:我搞砸了我的迁移,我该怎么办?May 13, 2025 am 12:06 AM

当您的inoumessupamigrationInlaravel,youcan:1)滚动播放'phpartisanmigrate:rollback'ifit'Sthelastone,or'phpartisanmigrate:reset'forall; 2)crecteAneAnewmigrateTocorrectRateRectRectRateRectRectRectRectRectRectRectRectErcrationInproduction; 3)

最后的Laravel版本:性能指南最后的Laravel版本:性能指南May 13, 2025 am 12:04 AM

toboostPerformanceInthelateStlaravelversion,关注详细信息:1)用户disforcachingtoimproveresponsetimes和Reddiccistatabaseload.2)优化的AtabasequesquesquesquesquesquesquesquesqueriesWitheAgerloadingTopreventn 1Queryissues.3)emplortecachingInprodododododododoductuproutroutrououtrououToreSourte。

最新的Laravel版本:DIFES DISCON最新的Laravel版本:DIFES DISCONMay 12, 2025 am 12:15 AM

Laravel10IntroducessEveralKeyFeatUrestHatenHanceWebDevelopment.1)LazyCollectionsAllyCollefficeProcesingOflargeFlargedAtasetSwithSwithOutloadingAllRecordSintomeMemory.2)the Make:Model Model Moged-and-Mogration'ArtisanCommandSancancMommandSimplififieScreatingModeltigation.3)

Laravel迁移解释了:创建,修改和管理您的数据库Laravel迁移解释了:创建,修改和管理您的数据库May 12, 2025 am 12:11 AM

laravelmigrationssshouldbeusedbecausetheystreamlinedeplupment,nesurecresistencyAcrossenviments和simplifyCollaborationAndDeployment.1)shemallogragrammatonofdatabaseschemachanges,ReeducingErrors.2)MigrigationScanBeverCanbeverSionConconconconcontrollin.2)

Laravel迁移:值得使用吗?Laravel迁移:值得使用吗?May 12, 2025 am 12:10 AM

是的。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境