这是工作队列
/**
* 推送消息到MQ队列
* @param $message //队列信息
* @param $exchange //交换机名
* @param $queue //队列名
* @param $kRoute //路由key
*/
public function publish($exchange, $queue, $kRoute, $messageBody)
{
$connection = new AMQPStreamConnection($this->host, $this->port, $this->login, $this->password, $this->vhost); // 创建连接
//创建频道
$channel = $connection->channel();
//创建queue
//RabbitMQ服务器停止,我们需要这么处理
//确保RabbitMQ不会失去我们的队列。为了这样做,
//我们需要声明它是耐用的。为此,我们将第三个参数传递给queue_declare为true
$channel->queue_declare($queue, false, true, false, false);
$channel->exchange_declare($exchange, 'fanout', false, false, false);
$channel->queue_bind($queue, $exchange); // 队列和交换器绑定
// 消息的持久化
$message = new AMQPMessage($messageBody,
array(
'content_type' => 'text/plain',
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT
)
);
$channel->basic_publish($message, $exchange, $queue); // 推送消息
$channel->close();
$connection->close();
}
/**
* 从MQ队列获取消息
*
* @param string $queue 队列名
* @return mixed 消息内容
*/
public function consumer($queue)
{
$connection = new AMQPStreamConnection($this->host, $this->port, $this->login, $this->password, $this->vhost); // 创建连接
$channel = $connection->channel();
$message = $channel->basic_get($queue); //取出消息
echo $message->body."\n";
//$channel->basic_ack($message->delivery_info['delivery_tag']); // 确认取出消息后会发送一个ack来确认取出来了
$callback = function($msg){
// echo $msg->body."\n";
sleep(substr_count($msg->body, '.'));
$msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
// echo $msg->body;
};
//在处理并确认前一个消息之前,不要向工作人员发送新消息
//$channel->basic_qos(null, 1, null);
$channel->basic_consume($queue, '', false, false, false, false, $callback);
while(count($channel->callbacks)) {
$channel->wait();
}
$channel->close();
$connection->close();
//return $message->body;
}