php 实现 activemq
使用 PHP 实现 ActiveMQ 通信
安装 Stomp 扩展
ActiveMQ 支持 STOMP 协议,PHP 可以通过 STomp 扩展与 ActiveMQ 通信。确保安装并启用 PHP 的 Stomp 扩展。
pecl install stomp
在 php.ini 中添加:
extension=stomp.so
连接到 ActiveMQ
使用 Stomp 客户端连接到 ActiveMQ 服务器。默认情况下,ActiveMQ 的 STOMP 端口为 61613。
$connection = new Stomp('tcp://localhost:61613');
$connection->connect();
发送消息到队列
发送消息到指定的队列或主题。以下示例发送消息到名为 test_queue 的队列。
$message = 'Hello, ActiveMQ!';
$connection->send('/queue/test_queue', $message);
echo "Message sent: $message\n";
订阅队列并接收消息
订阅队列并监听消息。以下示例监听 test_queue 队列并打印接收到的消息。
$connection->subscribe('/queue/test_queue');
while (true) {
if ($connection->hasFrame()) {
$frame = $connection->readFrame();
if ($frame != null) {
echo "Received: " . $frame->body . "\n";
$connection->ack($frame);
}
}
}
关闭连接
完成通信后,关闭连接以释放资源。
$connection->disconnect();
使用事务
如果需要确保消息的可靠性,可以使用事务发送消息。
$connection->begin();
$connection->send('/queue/test_queue', 'Transactional message');
$connection->commit();
错误处理
捕获并处理可能的异常,确保程序健壮性。
try {
$connection = new Stomp('tcp://localhost:61613');
$connection->connect();
$connection->send('/queue/test_queue', 'Test message');
} catch (StompException $e) {
echo "Error: " . $e->getMessage();
}
完整示例
以下是一个完整的发送和接收消息的示例。
<?php
try {
// 连接
$connection = new Stomp('tcp://localhost:61613');
$connection->connect();
// 发送
$connection->send('/queue/test_queue', 'Hello, ActiveMQ!');
// 接收
$connection->subscribe('/queue/test_queue');
while (true) {
if ($connection->hasFrame()) {
$frame = $connection->readFrame();
if ($frame != null) {
echo "Received: " . $frame->body . "\n";
$connection->ack($frame);
break;
}
}
}
// 关闭
$connection->disconnect();
} catch (StompException $e) {
echo "Error: " . $e->getMessage();
}
?>
注意事项
- 确保 ActiveMQ 服务器已启动并启用 STOMP 协议。
- 消息确认(ACK)是必要的,避免消息重复处理。
- 生产环境中建议使用更高级的消息处理模式(如持久化订阅)。







