header("Content-Type:text/html;charset=utf-8");
use Workerman\Worker;
require_once __DIR__ . '/Autoloader.php';
// 注意:这里与上个例子不同,使用的是websocket协议
$ws_worker = new Worker("websocket://192.168.1.218:5556");
// 启动4个进程对外提供服务
$ws_worker->count = 4;
// 当收到客户端发来的数据后返回hello $data给客户端
$ws_worker->onMessage = function($connection, $data)
{
$data = json_decode($data, true);
$conn_arg = array(
'host' => '192.168.1.100',
'port' => '5672',
'login' => 'qifaoa',
'password' => 'qifaoa@123',
'vhost' => '/',
);
foreach ($data as $k => $v) {
$exchange = $v;//交换机
$routing_key = $v;//路由key
$queue = $v;//队列
if (empty($exchange) || empty($routing_key) || empty($queue)) {
$connection->send('参数错误');
die();
}
//创建连接和channel
$conn = new AMQPConnection($conn_arg);
if (!$conn->connect()) {
$connection->send('rabbitmq连接失败');
die();
} else {
// echo '连接成功'."\n";
}
$channel = new AMQPChannel($conn);
//创建队列
$q = new AMQPQueue($channel);
$q->setName($queue);
$q->setFlags(AMQP_DURABLE);//设置队列持久化
$q->declareQueue();//声明创建队列
$q->bind($exchange, $routing_key);//绑定交换机,指定路由键
//消息获取
$message = $q->get(AMQP_AUTOACK);//自动应答机制
//判断消息是否存在
if ($message) {
$connection->send($message->getBody());
} else {
// echo json_encode('空');
}
$conn->disconnect();//关闭
}
};
//连接关闭
$ws_worker->onclose = function($connection) {
echo "connection close\n";
};
//连接错误
$worker->onError = function($connection, $code, $msg)
{
echo "error $code $msg\n";
};
// 运行worker
Worker::runAll();