PHP使用RabbitMQ实战

用composer安装rabbitmq客户端库:

composer require php-amqplib/php-amqplib

生产者:

 '127.0.0.1',
        'port' => 5672,
        'user' => 'guest',
        'pwd' => 'guest',
        'vhost' => '/',
];
$exchangeName = 'hello'; //交换机名
$queueName = 'test'; //队列名称
$routingKey = 'test'; //路由关键字(也可以省略)

$conn = new AMQPStreamConnection( //建立生产者与mq之间的连接
    $conf['host'], $conf['port'], $conf['user'], $conf['pwd'], $conf['vhost']
);
$channel = $conn->channel(); //在已连接基础上建立生产者与mq之间的通道


$channel->exchange_declare($exchangeName, 'direct', false, true, false); //声明初始化交换机
$channel->queue_declare($queueName, false, true, false, false); //声明初始化一条队列
$channel->queue_bind($queueName, $exchangeName, $routingKey); //将队列与某个交换机进行绑定,并使用路由关键字

$msgBody = json_encode(["contnet":"hello world"]);
$msg = new AMQPMessage($msgBody, ['content_type' => 'text/plain', 'delivery_mode' => 2]); //生成消息
$r = $channel->basic_publish($msg, $exchangeName, $routingKey); //推送消息到某个交换机

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

消费者:

 '127.0.0.1',
        'port' => 5672,
        'user' => 'guest',
        'pwd' => 'guest',
        'vhost' => '/',
];
$exchangeName = 'hello'; //交换机名
$queueName = 'test'; //队列名称
$routingKey = 'test'; //路由关键字(也可以省略)

$consumerTag = 'consumer';


$conn = new AMQPStreamConnection( //建立生产者与mq之间的连接
    $conf['host'], $conf['port'], $conf['user'], $conf['pwd'], $conf['vhost']
);
$channel = $conn->channel(); //在已连接基础上建立生产者与mq之间的通道


$channel->exchange_declare($exchangeName, 'direct', false, true, false); //声明初始化交换机
$channel->queue_declare($queueName, false, true, false, false); //声明初始化一条队列
$channel->queue_bind($queueName, $exchangeName, $routingKey); //将队列与某个交换机进行绑定,并使用路由关键字


//false 消息只有在返回一个ack之后,才会被删除,  true 消息被取出之后 会被立即删除
$no_ack = false;
$channel->basic_consume($queue, $consumerTag, false, $no_ack, false, false,function($msg){
    $message = $msg->body.PHP_EOL;
    echo $message;
    
    $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
});


while (count ($channel->callbacks)) {
    $channel->wait ();
}

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

 

你可能感兴趣的:(php,rabbitmq,php-amqp)