rabbitmq php 笔记

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
//生产者
public function send2(){
    //连接rabbitmq服务     主机  端口号   用户名   密码
    $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
    $channel = $connection->channel();
    //第三个参数为true时,表示队列持久化,需要和服务端一致
    $channel->queue_declare('task_queue', false, true, false, false);

    $data = "Hello World!";
    //设置delivery_mode表示设置消息持久化
    $msg = new AMQPMessage(
        $data,
        array('delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT)
    );
    //消息进入队列
    $channel->basic_publish($msg, '', 'task_queue');

    echo ' [x] Sent ', $data, "\n";
    //关闭
    $channel->close();
    $connection->close();
}
use PhpAmqpLib\Connection\AMQPStreamConnection;
//消费者 需要用cli模式
public function receive2(){

    $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
    $channel = $connection->channel();
    //将第三个参数改为true,第三个参数为true时,表示队列持久化,需要和客户端一致
    $channel->queue_declare('task_queue', false, true, false, false);

    echo " [*] Waiting for messages. To exit press CTRL+C\n";

    $callback = function ($msg) {
        echo ' [x] Received ', $msg->body, "\n";
        sleep(2);
        echo " [x] Done\n";
        /**** 这里执行业务逻辑****/
        //确认消息  消费者发回ack
        $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
    };
//当有多个消费者进行循环调度时,下面一行确保公平分发队列中的信息,每个消费者每次取一条
    $channel->basic_qos(null, 1, null);

    //从队列获取信息,并执行回调
    //第四个参数默认false 表示将进行消息确认,为true时不进行消息确认
    $channel->basic_consume('task_queue', '', false, false, false, false, $callback);

    while ($channel->is_consuming()) {
        $channel->wait();
    }

    $channel->close();
    $connection->close();

}

官方文档

https://xiaoxiami.gitbook.io/rabbitmq_into_chinese_php/ying-yong-jiao-cheng/php-ban/1-hello_world

你可能感兴趣的:(rabbitmq)