Laravel 使用 rabbitmq 非同步傳送郵件小案例.

程式碼的壞味道發表於2019-07-05

1.下載Erlang.rabbirmq的依賴環境

window官方下載地址官網:http://www.erlang.org/downloads
linux環境:rpm -Uvh http://www.rabbitmq.com/releases/erlang/erlang-18.1-1.el7.centos.x86_64.rpm 

2.下載RabbitMQ Server

window官方下載地址官網:http://www.rabbitmq.com/download.html,我是windows,直接下載安裝
linux環境: rpm -Uvh http://www.rabbitmq.com/releases/rabbitmq-server/v3.5.6/rabbitmq-server-3.5.6-1.noarch.rpm 

3.安裝成功後,window開啟rabbitmq 命令列。
linux:進入rabbitmq安裝目錄,../sbin
新增web管理端

rabbitmq-plugins enable rabbitmq_management

幾個常用命令:

  • service rabbitmq-server start
  • service rabbitmq-server restart
  • service rabbitmq-server stop
  • rabbitmqctl status

如下即安裝成功:
Laravel5.8 使用 rabbitmq 傳送郵件小案例.window,Linux 環境不同配置
4.瀏覽器輸入 http://127.0.0.1:15672
預設登入使用者:guest 密碼:guest
Laravel5.8 使用 rabbitmq 傳送郵件小案例.window,Linux 環境不同配置

1.laravel專案安裝composer命令列

composer require vladimir-yuldashev/laravel-queue-rabbitmq

2.在 config/app.php 檔案中,providers 中新增:

VladimirYuldashev\LaravelQueueRabbitMQ\LaravelQueueRabbitMQServiceProvider::class,

3.在 app/config/queue.php 配置檔案中的 connections 陣列中加入以下配置

 'rabbitmq' => [

            'driver' => 'rabbitmq',

            'dsn' => env('RABBITMQ_DSN', null),

            'factory_class' => Enqueue\AmqpLib\AmqpConnectionFactory::class,

            'host' => env('RABBITMQ_HOST', '127.0.0.1'),
            'port' => env('RABBITMQ_PORT', 5672),

            'vhost' => env('RABBITMQ_VHOST', '/'),
            'login' => env('RABBITMQ_LOGIN', 'guest'),
            'password' => env('RABBITMQ_PASSWORD', 'guest'),

            'queue' => env('RABBITMQ_QUEUE', 'default'),

            'options' => [

                'exchange' => [

                    'name' => env('RABBITMQ_EXCHANGE_NAME'),

                    /*
                     * Determine if exchange should be created if it does not exist.
                     */

                    'declare' => env('RABBITMQ_EXCHANGE_DECLARE', true),

                    /*
                     * Read more about possible values at https://www.rabbitmq.com/tutorials/amqp-concepts.html
                     */

                    'type' => env('RABBITMQ_EXCHANGE_TYPE', \Interop\Amqp\AmqpTopic::TYPE_DIRECT),
                    'passive' => env('RABBITMQ_EXCHANGE_PASSIVE', false),
                    'durable' => env('RABBITMQ_EXCHANGE_DURABLE', true),
                    'auto_delete' => env('RABBITMQ_EXCHANGE_AUTODELETE', false),
                    'arguments' => env('RABBITMQ_EXCHANGE_ARGUMENTS'),
                ],

                'queue' => [

                    /*
                     * Determine if queue should be created if it does not exist.
                     */

                    'declare' => env('RABBITMQ_QUEUE_DECLARE', true),

                    /*
                     * Determine if queue should be binded to the exchange created.
                     */

                    'bind' => env('RABBITMQ_QUEUE_DECLARE_BIND', true),

                    /*
                     * Read more about possible values at https://www.rabbitmq.com/tutorials/amqp-concepts.html
                     */

                    'passive' => env('RABBITMQ_QUEUE_PASSIVE', false),
                    'durable' => env('RABBITMQ_QUEUE_DURABLE', true),
                    'exclusive' => env('RABBITMQ_QUEUE_EXCLUSIVE', false),
                    'auto_delete' => env('RABBITMQ_QUEUE_AUTODELETE', false),
                    'arguments' => env('RABBITMQ_QUEUE_ARGUMENTS'),
                ],
            ],

            /*
             * Determine the number of seconds to sleep if there's an error communicating with rabbitmq
             * If set to false, it'll throw an exception rather than doing the sleep for X seconds.
             */

            'sleep_on_error' => env('RABBITMQ_ERROR_SLEEP', 5),

            /*
             * Optional SSL params if an SSL connection is used
             * Using an SSL connection will also require to configure your RabbitMQ to enable SSL. More details can be founds here: https://www.rabbitmq.com/ssl.html
             */

            'ssl_params' => [
                'ssl_on' => env('RABBITMQ_SSL', false),
                'cafile' => env('RABBITMQ_SSL_CAFILE', null),
                'local_cert' => env('RABBITMQ_SSL_LOCALCERT', null),
                'local_key' => env('RABBITMQ_SSL_LOCALKEY', null),
                'verify_peer' => env('RABBITMQ_SSL_VERIFY_PEER', true),
                'passphrase' => env('RABBITMQ_SSL_PASSPHRASE', null),
            ],

        ],

5.配置env檔案

QUEUE_CONNECTION=rabbitmq
RABBITMQ_HOST=127.0.0.1
RABBITMQ_PORT=5672
RABBITMQ_VHOST=/
RABBITMQ_LOGIN=guest
RABBITMQ_PASSWORD=guest
RABBITMQ_QUEUE=blog

6.建立一個佇列任務:php artisan make:job Queue

namespace App\Jobs;

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;
use Illuminate\Support\Facades\Redis;

class Queue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $email;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($email)
    {
        //
        $this->email=$email;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{
            $rand_num=$this->random(6,0);
            Redis::set($this->email,$rand_num);
            Mail::raw($rand_num, function ($message) {
                $message ->to($this->email)->subject('cfun部落格郵箱驗證');
            });
            echo json_encode(['code'=>200,'msg'=>'Success']);
        }catch (\Exception $exception) {
            echo json_encode(['code'=>0,'msg'=>$exception->getMessage()]);
        }

    }
}

7.建立一個控制器將佇列任務寫進去

namespace App\Http\Controllers;

use App\Http\Requests\SendEmailRequest;
use App\Jobs\Queue;

class IndexController extends Controller
{

  public function sendEmail(SendEmailRequest $request)
    {
        $email=$request->email;
        //註冊傳送郵件
        $this->dispatch(new Queue($email));
    }

}

8.配置郵箱env服務

MAIL_DRIVER=smtp
MAIL_HOST=smtp.qq.com//使用qq郵箱服務
MAIL_PORT=587
MAIL_FROM_ADDRESS=1606548133@qq.com
MAIL_USERNAME=1606548133@qq.com
MAIL_PASSWORD=xxxxxxx郵箱授權密碼
MAIL_FROM=1606548133@qq.com
MAIL_NAME=cfun

如果是線上可以配置supervisor管理,有興趣的同學自己配置看看.

php artisan queue:work
如果修改佇列任務程式碼,需要:PHP artisan cache:clear

本地訪問:
Laravel5.8 使用 rabbitmq 傳送郵件小案例.window,Linux 環境不同配置
線上linux環境訪問:
Laravel5.8 使用 rabbitmq 傳送郵件小案例.window,Linux 環境不同配置
最後注意:PHP需要開啟ampq擴充套件。如果有不懂的歡迎評論交流

本作品採用《CC 協議》,轉載必須註明作者和本文連結

cfun

相關文章