AMQP:工人将如何自动收听和执行

时间:2014-07-31 07:00:40

标签: php rabbitmq sendmail amqp worker

在PHP中实现AMQP并使电子邮件队列功能停留在如何工作文件或函数将自动调用?

如果在我执行之后放置工人的逻辑。但不确定它会起作用!

require_once('php-amqplib-master/amqp.inc');

class sendMailToQueue
{
    function __construct() 
    {
        $this->rabbitMQConf = array("host"=>"localhost","port"=>"5672","user"=>"guest","pass"=>"guest","virtualHost"=>"/");
    }

    function send($to,$subject,$text)
    {

        try {
            $conn = new AMQPConnection($this->rabbitMQConf['host'], 
            $this->rabbitMQConf['port'],
            $this->rabbitMQConf['user'],
            $this->rabbitMQConf['pass']);

            $channel = $conn->channel();
            $channel->queue_declare('task_queue', false, true, false, false);
            $mailData = array("to"=>$to,
            "subject"=>$subject,
            "text"=>$text);

            $mailDataToJson = json_encode($mailData);
            $msg = new AMQPMessage($mailDataToJson, array('content_type' => 'text/plain'));
            $channel->basic_publish($msg, '','task_queue');

            $callback = function($msg){
                $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);

                //my send mail logic comes here

                if(mail($to, $subject, $message, $headers)) {
                    echo "Email sent";
                }
                else {
                    echo "Email sending failed";
                }
            };    

            $channel->basic_qos(null, 1, null);
            $channel->basic_consume('task_queue', '', false, false, false, false, $callback);

            while(count($channel->callbacks)) {
                $channel->wait();
            }

            $channel->close();
            $conn->close();
            return true;
        }catch(Exception $e) {
            echo "Something went wrong ".$e->getMessage();
        }
   }
}
$mailSender = new sendMailToQueue();
$to = "user@gmail.com";
$subject = "This is a text message";
$text = "I show you how deep the rabbit-hole goes";
if ( $mailSender->send($to, $subject, $text ) ) {
    echo "Mail sent to queue"; 
}

提前致谢。

0 个答案:

没有答案