1.查看activemq配置(conf/activemq.xml)
<transportConnector name="stomp" uri="stomp://0.0.0.0:61605?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
确保stomp协议可用
2.使用composer安装php扩展
composer require fusesource/stomp-php:2.0.*
3.生产者代码
//queue方式 public function simpleSend(){ try{ $isSend = false; //实例化Stomp //集群方式 $connection = new Stomp('failover://(tcp://192.168.2.184:61603,tcp://192.168.2.184:61604,tcp://192.168.2.184:61605)?randomize=false'); //单节点方式 //$connection = new Stomp('tcp://192.168.2.184:61603'); //连接 $connection -> connect(); //开启事务,确保持久化消息的异步发送 $connection -> begin('test'); //消息持久化 for ($i = 0;$i < 100;$i++){ $connection -> send('/queue/test', 'test hello'.$i,array('persistent'=>'true')); } $connection -> commit('test'); $connection -> disconnect(); }catch (StompException $e){ echo $e -> getMessage(); //关闭连接 if(isset($connection)){ if($connection -> isConnected()){ $connection -> disconnect(); exit; } } if(!$isSend){ echo '消息未被发送'; } } } //topic方式 public function topicSend(){ try{ $isSend = false; //实例化Stomp $connection = new Stomp('failover://(tcp://192.168.2.184:61603,tcp://192.168.2.184:61604,tcp://192.168.2.184:61605)?randomize=false'); //单节点方式 //$connection = new Stomp('tcp://192.168.2.184:61603'); //连接 $connection -> connect(); //开启事务,确保持久化消息的异步发送 $connection -> begin('test'); //消息持久化 for ($i = 0;$i < 100;$i++){ $connection -> send('/topic/topictest', 'test hello '.$i,array('persistent'=>'true')); } $connection -> commit('test'); $connection -> disconnect(); }catch (StompException $e){ echo $e -> getMessage(); //关闭连接 if(isset($connection)){ if($connection -> isConnected()){ $connection -> disconnect(); exit; } } if(!$isSend){ echo '消息未被发送'; } } }
4.消费者代码
//点对点通信消费者 private function simpleConsumer(){ try{ //多个消费者的公平策略,轮询策略或单线程处理去掉jms.prefetchPolicy.all=2 $connection = new Stomp("tcp://192.168.2.184:61613"); $connection -> connect(); $connection -> subscribe('/queue/test'); while ($connection -> hasFrameToRead()){ //获取消息 $msg = $connection -> readFrame(); echo "=====>".$msg -> body; sleep(3); $connection -> ack($msg); } }catch (StompException $e){ echo $e -> getMessage(); //关闭连接 if(isset($connection)){ if($connection -> isConnected()){ $connection -> disconnect(); exit; } } $connection -> unsubscribe('/queue/test'); } } //topic通信消费者 private function topicConsumer(){ try{ //多个消费者的公平策略,轮询策略或单线程处理去掉jms.prefetchPolicy.all=2 $connection = new Stomp("tcp://192.168.2.184:61613"); $connection -> connect(); $connection -> subscribe('/topic/topictest'); while ($connection -> hasFrameToRead()){ //获取消息 $msg = $connection -> readFrame(); echo "=====>".$msg -> body; sleep(3); $connection -> ack($msg); } }catch (StompException $e){ echo $e -> getMessage(); //关闭连接 if(isset($connection)){ if($connection -> isConnected()){ $connection -> disconnect(); exit; } } $connection -> unsubscribe('/topic/topictest'); } }