https://www.jb51.net/article/121647.htmphp
本文主要給你們介紹了關於Laravel中隊列發送郵件的相關內容,分享出來供你們參考學習,下面話很少說了,來一塊兒看看詳細的介紹:mysql
批量處理任務的場景在咱們開發中是常常使用的,好比郵件羣發,消息通知,短信,秒殺等等,咱們須要將這個耗時的操做放在隊列中來處理,從而大幅度縮短Web請求和相應的時間。下面講解下Laravel中隊列的使用
laravel
一、配置文件 config/queue.php
redis
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
<?php
return
[
'default'
=> env(
'QUEUE_DRIVER'
,
'sync'
),
'connections'
=> [
'sync'
=> [
'driver'
=>
'sync'
,
],
'database'
=> [
'driver'
=>
'database'
,
'table'
=>
'jobs'
,
'queue'
=>
'default'
,
'retry_after'
=> 90,
],
'beanstalkd'
=> [
'driver'
=>
'beanstalkd'
,
'host'
=>
'localhost'
,
'queue'
=>
'default'
,
'retry_after'
=> 90,
],
'sqs'
=> [
'driver'
=>
'sqs'
,
'key'
=>
'your-public-key'
,
'secret'
=>
'your-secret-key'
,
'queue'
=>
'your-queue-name'
,
'region'
=>
'us-east-1'
,
],
'redis'
=> [
'driver'
=>
'redis'
,
'connection'
=>
'default'
,
'queue'
=>
'default'
,
'retry_after'
=> 90,
],
],
'failed'
=> [
'database'
=> env(
'DB_CONNECTION'
,
'mysql'
),
'table'
=>
'failed_jobs'
,
],
];
|
配置文件默認使用的是同步驅動sync,每一種隊列驅動的配置均可以在該文件中找到, 包括數據庫, Beanstalkd, Amazon SQS, Redis。 其中還包含了一個null隊列驅動用於那些放棄隊列的任務。failed配置項用於配置失敗隊列任務存放的數據庫及數據表。 接下來咱們須要建立一個隊列任務類。具體配置能夠參考文檔 隊列驅動配置
sql
二、建立隊列任務類,以後會在app/Jobs目錄下生成一個SendEmail.php的文件
數據庫
1
|
php artisan make:job SendEmail
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
<?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(
'這裏填寫郵件的內容'
,
function
(
$message
){
// 發件人(你本身的郵箱和名稱)
$message
->from(
'your_email@163.com'
,
'yourname'
);
// 收件人的郵箱地址
$message
->to(
$this
->user);
// 郵件主題
$message
->subject(
'隊列發送郵件'
);
});
}
}
|
任務類建立完以後到控制器 把數據加入到隊列
瀏覽器
三、建立發送消息的控制器 使用dispatch方法手動分發任務,方法裏傳一個任務類的實例
app
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?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 --daemon ,當更新代碼的時候,須要中止,而後從新啓動,這樣才能把修改的代碼應用上。
總結
以上就是這篇文章的所有內容了,但願本文的內容對你們的學習或者工做能帶來必定的幫助,若是有疑問你們能夠留言交流,謝謝你們對腳本之家的支持。
出現問題去failed_jobs表中查看信息