rabbitMQ模擬訊息佇列群發郵件
阿新 • • 發佈:2018-12-25
首先我們寫一個傳送頁面,第一步就建立與rabbitmq的建立,然後建立通道,接下來建立通道內的交換機,之後進行定義交換機的名稱和型別,交換機進行持久化,以後無論何時重新啟動rabbitmq,資料都不會消失,接下請欣賞程式碼
<?php $config = [ 'host' => '127.0.0.1', 'vhost' => '/', 'port' => 5672, 'login' => 'lirui', 'password' => 'lirui' ]; //連線 $conn = new \AMQPConnection($config); $conn->connect(); //建立通道 $channel = new \AMQPChannel($conn); //建立通道內的交換機 $exchange = new \AMQPExchange($channel); //定義交換機的名稱和型別 $exchange->setName('exchange.li'); $exchange->setType(AMQP_EX_TYPE_DIRECT); //交換機持久化 $exchange->setFlags(AMQP_DURABLE); $exchange->declareExchange(); //建立佇列 $queue = new \AMQPQueue($channel); $queue->setName('queue.liu'); $queue->setFlags(AMQP_DURABLE); $queue->declareQueue(); $queue->bind('exchange.li','route.rui'); $data=[ [ "tomail"=>"
[email protected]", "title"=>"先生.你好飄了", "content"=>"我就是試試qq我就是試試qq我就是試試qq" ], [ "tomail"=>"[email protected]", "title"=>"好使就行啦", "content"=>"再來一次哦,哈哈哈" ] ]; $result = $exchange->publish(json_encode($data),'route.rui'); var_dump($result); ?>
之後就是進行接收資訊頁面,並進行處理髮送郵件給使用者,在傳送之前需進行定義一個傳送郵件的類,之後便可直接進行傳送
<?php
use PHPMailer\PHPMailer\PHPMailer;
require_once('src/PHPMailer.php');
require_once('src/SMTP.php');
require_once('src/Exception.php');
class Semails{
public function sendM($tomail,$title,$content){
$mail = new PHPMailer(true);
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.qq.com';
$mail->SMTPAuth = true;
$mail->Username = '1049561244';
$mail->Password = '***';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom(' [email protected]', '***');
$mail->addAddress($tomail);
$mail->isHTML(true);
$mail->Subject = $title;
$mail->Body = $content;
$res=$mail->send();
if($res)
{
return 1;
}
else
{
return 0;
}
}
}
?>
<?php
set_time_limit(0);
$config = [
'host' => '127.0.0.1',
'vhost' => '/',
'port' => 5672,
'login' => 'lirui',
'password' => 'lirui'
];
$conn = new \AMQPConnection($config);
$conn->connect();
$channel = new \AMQPChannel($conn);
$channel->qos(0,0);
$queue = new \AMQPQueue($channel);
$queue->setName("queue.liu");
$queue->setFlags(AMQP_PASSIVE);
$queue->declareQueue();
$queue->bind('exchange.li','route.rui');
$queue->consume('processMessage',AMQP_AUTOACK);
function processMessage($envelope, $queue) {
require_once "email/sendEmail.php";
$e=new Semails();
$mail=$envelope->getBody();
$mail=json_decode($mail,true);
foreach($mail as $k=>$v){
$res=$e->sendM($v['tomail'],$v['title'],$v['content']);
if($res)
{
echo "Good\n";
}else{
echo "error";
}
}
}
?>
rabbitmq這樣操作可以增加使用者的體驗,同時還可以減少伺服器的壓力。
若有什麼更加完善的技術或者建議:[email protected]