amqplib php 简介

1.安装amqplib:
    项目中添加composer.json:
    {
        "require":{
            "php-amqplib/php-amqplib":"2.6.1"
        }
    }
    cmd到项目目录下,如果之前已经安装:composer update  然后composer install。如果之前没有安装:composer install
2.发送消息到队列:
    require_once __DIR__ . "/vendor/autoload.php";
    use PhpAmqplib\Connection\AMQPStreamConnection;
    use PhpAmqpLib\Message\AMQPMessage;
    $connection = new AMQPStreamConnection("localhost",5672,"guest","guest");//建立连接
    $channel = $connection->channel();//建立通道
    $channel->queue_declare("hello",false,false,false,false);//声明队列
    $msg = new AMQPMessage("hello Wprld!");
    $channel->basic_publish($msg,"","hello");//发送消息到队列
    $channel->close();//关闭通道
    $connection->close();//关闭连接
3.从队列接收消息:
    $connection = new AMQPStreamConnection("localhost",5672,"guest","guest");;
    $channel = $connection->channel();
    $channel->queue_declare("hello",false,false,false,false);
    $callback = function($msg){
        echo " [x] Received ",$msg->body, "\n";
    };
    $channel->basic_consume("hello","",false,true,false,false,$callback);
    while(count($channel->callbacks)){
        $channel->wait();
    }

猜你喜欢

转载自blog.csdn.net/xyy_forever/article/details/81704858
今日推荐