rabbitMQ-PHP

这是工作队列  
/**
     * 推送消息到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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值