异步发送邮件完整示例

邮件类
下载swiftmailer
composer require “swiftmailer/swiftmailer:^6.0”

Mailer.php 与 vender目录 同级

require_once DIR . ‘/vendor/autoload.php’;

class Mailer
{
public $transport;
public $mailer;
/**
* 发送邮件类 参数 d a t a 需 要 三 个 必 填 项 包 括 邮 件 主 题 ‘ data 需要三个必填项 包括 邮件主题` datadata[‘subject’]、接收邮件的人 d a t a [ ′ t o ′ ] ‘ 和 邮 件 内 容 ‘ data['to']`和邮件内容 ` data[to]data[‘content’]`
* @param Array $data
* @return bool r e s u l t 发 送 成 功 o r 失 败 ∗ / p u b l i c f u n c t i o n s e n d ( result 发送成功 or 失败 */ public function send( resultor/publicfunctionsend(data)
{
$this->transport = (new Swift_SmtpTransport(‘smtp.qq.com’, 25))
->setEncryption(‘tls’)
->setUsername(‘bailangzhan@qq.com’)
->setPassword(‘xxxxxx’);
t h i s − > m a i l e r = n e w S w i f t M a i l e r ( this->mailer = new Swift_Mailer( this>mailer=newSwiftMailer(this->transport);

    $message = (new Swift_Message($data['subject']))
        ->setFrom(array('bailangzhan@qq.com' => '白狼栈'))
        ->setTo(array($data['to']))
        ->setBody($data['content']);
        
    $result = $this->mailer->send($message);

    // 释放
    $this->destroy();
    return $result;
}
public function destroy()
{
    $this->transport = null;
    $this->mailer = null;
}

}

Server
后端启动:php server.php
这里单独拆分了一个TaskRun类,并且在onWorkerStart之后进行载入,主要是为了之后的“平滑重启“

class TaskServer
{
private $_serv;
private $_run;

public function __construct()
{
    $this->_serv = new Swoole\Server("127.0.0.1", 9501);
    $this->_serv->set([
        'worker_num' => 2,
        'daemonize' => false,    //是否开启守护进程
        'log_file' => __DIR__ . '/server.log',    //守护进程调试日志
        'task_worker_num' => 2,
        'max_request' => 5000,    //防止内存泄漏
        'task_max_request' => 5000,    //防止内存泄漏
        'package_eof' => "\r\n", //设置EOF
        'open_eof_split' => true, // 自动分包
    ]);
    $this->_serv->on('Connect', [$this, 'onConnect']);
    $this->_serv->on('Receive', [$this, 'onReceive']);
    $this->_serv->on('WorkerStart', [$this, 'onWorkerStart']);
    $this->_serv->on('Task', [$this, 'onTask']);
    $this->_serv->on('Finish', [$this, 'onFinish']);
    $this->_serv->on('Close', [$this, 'onClose']);
}
public function onConnect($serv, $fd, $fromId)
{
}
public function onWorkerStart($serv, $workerId)
{
    require_once __DIR__ . "/TaskRun.php";
    $this->_run = new TaskRun;
}
public function onReceive($serv, $fd, $fromId, $data)
{
    $data = $this->unpack($data);
    $this->_run->receive($serv, $fd, $fromId, $data);
    // 投递一个任务到task进程中
    if (!empty($data['event'])) {
        $serv->task(array_merge($data , ['fd' => $fd]));
    }
}
public function onTask($serv, $taskId, $fromId, $data)
{
    $this->_run->task($serv, $taskId, $fromId, $data);
}
public function onFinish($serv, $taskId, $data)
{
    $this->_run->finish($serv, $taskId, $data);
}
public function onClose($serv, $fd, $fromId)
{
}
/**
* 对数据包单独处理,数据包经过`json_decode`处理之后,只能是数组
* @param $data
* @return bool|mixed
*/
public function unpack($data)
{
    $data = str_replace("\r\n", '', $data);
    if (!$data) {
        return false;
    }
    $data = json_decode($data, true);
    if (!$data || !is_array($data)) {
        return false;
    }
    return $data;
}
public function start()
{
    $this->_serv->start();
}

}
$reload = new TaskServer;
$reload->start();

TaskRun 业务类
当此处修改了代码后,可以进行平滑重启,因为他是在Server端的onWorkerStart之后加载的文件。
require_once (’./Mailer.php’);
class TaskRun
{
public function receive($serv, $fd, $fromId, d a t a ) p u b l i c f u n c t i o n t a s k ( data) { } public function task( data)publicfunctiontask(serv, $taskId, $fromId, KaTeX parse error: Expected '}', got 'EOF' at end of input: … switch (data[‘event’]) {
case ‘send-mail’:
$mailer = new Mailer;
$result = m a i l e r − > s e n d ( mailer->send( mailer>send(data);
break;
default:
break;
}
return $result;
} catch (\Exception $e) {
throw new \Exception(‘task exception :’ . KaTeX parse error: Expected 'EOF', got '}' at position 27: …ge()); }̲ } publ…serv, $taskId, $data)
{
return true;
}
}

Client
client加了eof,为了防止粘包,通过网址访问该程序

$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);

KaTeX parse error: Expected '}', got 'EOF' at end of input: …ailed. Error: {client->errCode}\n");

$data = [
‘event’ => ‘send-mail’,
‘to’ => ‘5566***@qq.com’,
‘subject’ => ‘just a test’,
‘content’ => ‘This just a test.’,
];

c l i e n t − > s e n d ( t o g e t h e r D a t a B y E o f ( client->send(togetherDataByEof( client>send(togetherDataByEof(data)); //发送数据给服务端

$client->close(); //关闭连接

/**

  • 数据末尾拼接EOF标记
  • @param Array $data 要处理的数据
  • @return String json_encode( d a t a ) . E O F ∗ / f u n c t i o n t o g e t h e r D a t a B y E o f ( data) . EOF */ function togetherDataByEof( data).EOF/functiontogetherDataByEof(data)
    {
    if (!is_array( d a t a ) ) r e t u r n f a l s e ; r e t u r n j s o n e n c o d e ( data)) { return false; } return json_encode( data))returnfalse;returnjsonencode(data) . “\r\n”;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值