一、下载stomp包
composer require stomp-php/stomp-php
二、演示
$arr = getopt("", ['func:']);
if (empty($arr)) exit("执行错误");
$func = $arr['func'];
if ($func == "sub") {
subClient();
} elseif ($func == 'pub') {
pubClient();
}
function subClient()
{
//订阅队列消息
$connection = new Connection("tcp://101.132.172.189:61613");
$connection->setReadTimeout(1);
$stomp = new StatefulStomp(new Client($connection));
$stomp->subscribe('email', null, 'client');
do{
$frame = $stomp->read();
if ($frame != false) {
$channel = $frame->getHeaders()['destination']; //获取消息通道
$message = $frame->body; //获取消息推送体
echo "订阅频道 [{$channel}] 接受消息内容 [{$message}]" . PHP_EOL;
sleep(2); //处理业务逻辑耗时
$stomp->ack($frame);//通知mq,已处理消息
}
}while(true);
}
function pubClient()
{
$connection = new Client("tcp://101.132.172.189:61613");
$stomp = new StatefulStomp($connection);
$stomp->begin();
$obj = new StdClass();
$obj->username = "Mis_wang";
$obj->password = password_hash("123123", PASSWORD_DEFAULT);
$stomp->send('email', new Message(json_encode($obj)), array('persistent'=>'true')); //持久化消息内容
$stomp->commit();
}
订阅
发布
看到我这里已经入队了,也出队执行任务了,所以就ok了
当然如果只入队,没有进行出队的处理,那么这个队列消息就处于排队中,可以在mq后台看到