gearman初探:(三、异步发送邮件)

经过前面的工作,一切就绪。下面就开始最最重点的部分——异步发送邮件

在发送邮件之前,先用gearman官网上的例子热热身

client.php:

<?php
$client = new GearmanClient();
$client->addServer();
echo $client->do("reverse", "Hello World!");
?>

worker.php:

<?php
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction("reverse", function ($job) {
  return strrev($job->workload());
});
while ($worker->work());
?>
Client 和 Worker 都需要通过addServer函数连接到服务器上,默认主机是127.0.0.1,默认端口是4730
代码部署好之后,运行Worker
#php ./worker.php

让worker一直处于循环等待工作请求的状态

然后运行Client

#php ./client.php

这时你会看到一串被反转的hello world!    说明系统已正常工作。

我们正式使用Gearman来发送邮件,代码如下:

client.php

<?php
$client = new GearmanClient();
$client->addServer();
echo $client->do("sendmail", "Hello World!");
?>

workder.php

<?php
require_once 'mail/PHPMailerAutoload.php';
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction("sendmail", function ($job) {
            $mail = new PHPMailer;
            //$mail->SMTPDebug = 3;                   // Enable verbose debug output
            $mail->isSMTP();                         // Set mailer to use SMTP
            $mail->Host = 'smtp.qq.com';  // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                  // Enable SMTP authentication
            $mail->Username = '[email protected]';        // SMTP username
            $mail->Password = 'yyyyy';                 // SMTP password
            $mail->SMTPSecure = 'tls';  // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 587;                      // TCP port to connect to

            $mail->From = '[email protected]';
            $mail->FromName = 'Mailer';
            $mail->addAddress('[email protected]', 'Joe User');  // Add a recipient

            $mail->WordWrap = 50;                    // Set word wrap to 50 character
            $mail->isHTML(true);                     // Set email format to HTML

            $mail->Subject = 'Here is the subject';
            $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
            if(!$mail->send()) {
                	    echo 'Message could not be sent.';
                    	 echo 'Mailer Error: ' . $mail->ErrorInfo;
            } else {
                    	 echo 'Message has been sent';
            }
            return true;
    });
    while ($worker->work());
?>

mail为邮件发送类库所在文件夹,注意它的位置 要让worker.php能引用到它。 

运行workder.php,然后运行client.php。邮件发送出去后,worker端会收到一个成功消息。这时候你会发现client 依然是被阻塞的,要等到邮件被发送出去后才返回。那是因为client的do方法是同步的,改为doBackground就是异步的,这时发现client立即返回了,邮件放在后台发送。这样程序不必等待就可以继续往下执行,用户体验很好。 


现在的client,worker和job server都在同一台机器上,如果计算任务量比较大,可以准备几台机器专门做worker,只要client和worker都能连上job server,系统就会正常运作,从而真正达到分布式异步计算的目的。

你可能感兴趣的:(gearman初探:(三、异步发送邮件))