rabbitMQ模拟消息队列群发邮件

首先我们写一个发送页面,第一步就建立与rabbitmq的建立,然后创建通道,接下来创建通道内的交换机,之后进行定义交换机的名称和类型,交换机进行持久化,以后无论何时重新启动rabbitmq,数据都不会消失,接下请欣赏代码

 '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);

 ?>

之后就是进行接收信息页面,并进行处理发送邮件给用户,在发送之前需进行定义一个发送邮件的类,之后便可直接进行发送

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;
        }
    }
}
    

 ?>

 '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]


你可能感兴趣的:(newCode,rabbitmq)