think-queue使用教程-用戶註冊場景異步發送郵件

think-queue使用教程-用戶註冊場景異步發送郵件
本地環境:
系統是:Mac Os
php版本:7.1
ThinkPHP版本:5.1.15php

最近看到think-queue這個擴展類 可是手冊沒寫,非常頭疼,找了不少資料最後寫了個場景,寫的很差你們見諒
首先咱們建立項目 下載tp框架以及think-queue擴展redis

建立項目:
5b18405a31cc9.png
進入項目目錄查看:
5b18407d3eee4.png數據庫

下載擴展類
5b18409d09708.pngapp

下載完畢進入查看一下:
5b1840b079010.png框架

以後使用MAMP(媽賣麻痹)建立虛擬機
5b1840d47b4c3.png異步

以後建立數據庫以及數據表;post

create database if not exists myproject;
use myproject;
DROP TABLE IF EXISTS member;
CREATE TABLE IF NOT EXISTS member(
  id int(11) AUTO_INCREMENT primary key comment 'ID',
  email VARCHAR(32) NOT NULL DEFAULT '' COMMENT '',
  password VARCHAR(255) NOT NULL default '' comment '',
  create_time INT(11) UNSIGNED NOT NULL DEFAULT 0 comment '',
  update_time INT(11) UNSIGNED NOT NULL DEFAULT 0 comment '',
  unique key (email)
)engine innodb charset utf8;

啓動redis 服務
5b18413474dc1.pngfetch

以後一些列的操做,好比開啓強制路由,配置數據庫,配置路由,配置模板標籤等....網站

建立頁面Register.php控制器 目錄:application/index/controller/Register.php
建立Member.php 模型 目錄:application/index/model/Member.php
建立Register.php 驗證器 目錄:application/index/validate/Register.php
建立處理隊列的文件 sendActivationMail.php 目錄:application/index/job/sendActivationMail.phpthis

在Register控制器裏面建立操做方法

<?php
/**
 * User: 李昊天
 * Date: 18/6/7
 * Time: 上午3:15
 * Email: haotian0607@gmail.com
 */

namespace app\index\controller;

use think\Controller;
use app\index\model\Member as MemberModel;
use app\index\validate\Register as RegisterValidate;
use think\Queue;

class Register extends Controller
{
    private $model = '';

    public function initialize()
    {
        $this->model = new MemberModel();
    }

    /**
     * 渲染模板 展現註冊頁面
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index');
    }

    /**
     * 執行註冊邏輯
     */
    public function doRegister()
    {
        if ($this->request->isPost()) {
            #實例化驗證器 執行驗證 若是驗證失敗跳轉而且提示
            $validate = new RegisterValidate();
            $data = $this->request->post();
            if (false === $validate->check($data)) return $this->error($validate->getError());
            //此處應該加密密碼 md5 sha1 hash 均可以
            //寫入註冊的用戶
            $result = $this->model->allowField(['email', 'password'])->save($data);
            if ($result) {
                //註冊完畢後獲取到郵件帳號  而後加入到隊列
                $this->sendActivationMail($this->model->email);
                return $this->success('註冊成功,請前往郵箱激活您的帳號!');
            } else {
                return $this->error('註冊失敗');
            }
        }
    }

    /**
     * @param string $email 郵箱帳號
     */
    private function sendActivationMail($email = '')
    {
        $jobName = 'app\index\job\sendActivationMail';  //負責處理隊列任務的類
        $data = ['email' => $email]; //當前任務所需的業務數據
        $jobQueueName = 'sendActivationMail'; //當前任務歸屬的隊列名稱,若是爲新隊列,會自動建立


        $result = Queue::push($jobName, $data, $jobQueueName);

        if ($result) {
            echo date('Y-m-d H:i:s') . '一個新的隊列任務';
        } else {
            echo date('Y-m-d H:i:s') . '添加隊列出錯';
        }

        // php think queue:work --queue sendActivationMail --daemon
    }
}

sendActivationMail.php 代碼

<?php
/**
 * User: 李昊天
 * Date: 18/6/7
 * Time: 上午3:36
 * Email: haotian0607@gmail.com
 */

namespace app\index\job;

use think\queue\Job;
use PHPMailer\Mail;
use think\Exception;

class sendActivationMail
{
    /**
     * fire方法是消息隊列默認調用的方法
     * @param Job $job 當前的任務對象
     * @param $data 發佈任務時自定義的數據
     */
    public function fire(Job $job, $data)
    {
        //執行發送郵件
        $isJobDone = $this->sendMail($data);

        //若是發送成功  就刪除隊列
        if ($isJobDone) {
            print ("<warn>任務執行成功,,已經刪除!" . "</warn>\n");
            $job->delete();
        } else {
            //若是執行到這裏的話 說明隊列執行失敗  若是失敗三次就刪除該任務  不然從新執行
            print ("<warn>任務執行失敗!" . "</warn>\n");
            if ($job->attempts() > 3) {
                print ("<warn>刪除任務!" . "</warn>\n");
                $job->delete();
            } else {

                $job->release(); //重發任務
                print ("<info>從新執行!第" . $job->attempts() . "次從新執行!</info>\n");
            }
        }
    }

    /**
     * 發送郵件
     * @param $data
     * @return bool
     */
    private function sendMail($data)
    {
        $title = '帳號激活郵件';
        $msg = '歡迎您註冊xxx網站,您的請點擊一下鏈接激活您的帳號!....';
        try {
            return Mail::send($title, $msg, $data['email']);
        } catch (Exception $e) {
            return false;
        }
    }
}

寫完以後再控制器切換到當前目錄下 執行

php think queue:work --queue sendActivationMail --daemon

5b18435b1596b.png

代碼裏面有很詳細的註釋,可是這個並不完整,,,沒有錯誤的回調,等下次有時間的時候再寫剩下的代碼!

相關文章
相關標籤/搜索