Php AMQP:工作人员将如何自动侦听和执行
在PHP中实现AMQP并实现电子邮件队列功能,但仍停留在如何自动调用工作文件或函数上 如果把工人的逻辑放在我的任务执行之后。但我不确定这样行不行Php AMQP:工作人员将如何自动侦听和执行,php,rabbitmq,sendmail,amqp,worker,Php,Rabbitmq,Sendmail,Amqp,Worker,在PHP中实现AMQP并实现电子邮件队列功能,但仍停留在如何自动调用工作文件或函数上 如果把工人的逻辑放在我的任务执行之后。但我不确定这样行不行 require_once('php-amqplib-master/amqp.inc'); class sendMailToQueue { function __construct() { $this->rabbitMQConf = array("host"=>"localhost","port"=>
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";
}
提前感谢。您似乎正在使用非常旧的php amqplib版本。看到为什么要在同一个文件上发布和使用了吗?也许看看这里:实际上,我在想,要让worker执行,我需要每次调用它,但要知道,在部署时,只要队列声明它将自动执行,就需要启动该worker。谢谢@old_sound的帮助,但是:是的,您只需运行一次workers,他们就会一直监听传入的消息