我不确定此问题是否与stomp-php或ActiveMQ Docker相关(使用默认值运行)。
我有一个用PHP编写的简单Queue助手类,它处理将消息发送到队列(Queue::push
),以及消耗它(Queue::fetch
)。请参阅下面的代码。
如您所见,fetch()
应订阅队列,阅读一条消息并取消订阅。应自动确认消息(\Stomp\StatefulStomp::subscribe()
,第3个参数)。
出于某种原因,客户会收到约5-7%的消息,甚至是两次。 为何多次发送邮件以及如何避免邮件?
发布者(推送1000条消息):
$mq = new Queue('tcp://activemq:61613','test');
for ($msgCount = 0; $msgCount < 1000; $msgCount++) {
$mq->push('Message #' . $msgCount);
}
消费者(接收约1070条消息):
$mq = new Queue('tcp://activemq:61613','test');
$received = 0;
while (true) {
$message = $mq->fetch();
if (null === $message) { break; }
$received++;
}
队列类代码:
use Stomp\Client;
use Stomp\Network\Connection;
use Stomp\SimpleStomp;
use Stomp\StatefulStomp;
use Stomp\Transport\Message;
class Queue
{
/**
* @var \Stomp\StatefulStomp
*/
private $stomp;
private $queue;
public function __construct($uri, $queue) {
$connection = new Connection('tcp://activemq:61613');
$this->stomp = new StatefulStomp(new Client($connection));
$connection->setReadTimeout(1);
$this->queue = $queue;
}
public function push($body) {
$message = new Message($body, ['activemq.maximumRedeliveries' => 0]);
$this->stomp->send('/queue/' . $this->queue, $message);
}
public function fetch() {
$subscriptionId = $this->stomp->subscribe('/queue/' . $this->queue, null, 'auto', ['activemq.prefetchSize' => 1]);
$msg = $this->stomp->read();
$this->stomp->unsubscribe($subscriptionId);
return $msg;
}
}