消费者 comsumer.php
<?php
/**
* 消费者
*/
$workerNum = 4;
$pool = new Swoole\Process\Pool($workerNum);
//绑定一个事件
$pool->on("WorkerStart", function ($pool, $workerId) {
echo "Worker#{$workerId} is started\n";
//单个进程必须独占一个连接
rabbitMqServer($workerId);
});
//进程关闭
$pool->on("WorkerStop", function ($pool, $workerId) {
echo "Worker#{$workerId} is stopped\n";
});
$pool->start();
function rabbitMqServer($workerId = 0)
{
try {
$exchangeName = 'trade';
$routeKey = '/trade';
$queueName = 'trade';
//建立连接
$conn = new AMQPConnection([
'host' => '127.0.0.1',
'port' => 5672,
'vhost' => '/',
'login' => 'guest',
'password' => 'guest',
]);
$conn->connect();
//创建通道
$channel = new AMQPChannel($conn);
//创建队列
$queue = new AMQPQueue($channel);
$queue->setName($queueName);
$queue->declareQueue();
//绑定路有关系监听
$queue->bind($exchangeName, $routeKey);
//消费[没有数据就是阻塞状态,有数据才会执行]
$queue->consume(function ($envelope, $queue) use ($workerId) {
var_dump($workerId);
var_dump($envelope->getBody());
$queue->ack($envelope->getDeliveryTag());//分布式手动应答机制
});
} catch (\Exception $exception) {
var_dump($exception);
}
}
生产者 producer.php
<?php
/**
* 生产者
*/
try{
$exchangeName = 'trade';
$routeKey = '/trade';
//建立连接
$conn = new AMQPConnection([
'host'=>'127.0.0.1',
'port'=>5672,
'vhost'=>'/',
'login'=>'guest',
'password'=>'guest',
]);
$conn->connect();
//创建通道
$channel = new AMQPChannel($conn);
//创建交换机
$exchange = new AMQPExchange($channel);
$exchange->setName($exchangeName);
$exchange->setType(AMQP_EX_TYPE_DIRECT);
$exchange->declareExchange();
$data = [
'msg_type' => 'trade',
'tid'=> uniqid()
];
//绑定路由关系发送消息
$exchange->publish(json_encode($data),$routeKey);
}catch (\Exception $exception){
var_dump($exception);
}
生产者即为客户端,由客户端发生任务,然后通过swoole的进程池去调用rabbitmq执行消费。
控制台执行comsumer.php,挂起消费者监听。
执行producer.php,发送任务,在消费端可看到进程号和接收到消息的输出。