workerman/rabbitmq

workerman/rabbitmq是一个异步RabbitMQ客户端,使用AMQP协议。

项目地址:

https://github.com/walkor/rabbitmq

安装:

  1. composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
  2. composer require workerman/rabbitmq

示例

receive.php

  1. <?php
  2. use Bunny\Channel;
  3. use Bunny\Message;
  4. use Workerman\Worker;
  5. use Workerman\RabbitMQ\Client;
  6. require __DIR__ . '/vendor/autoload.php';
  7. $worker = new Worker();
  8. $worker->onWorkerStart = function() {
  9. (new Client())->connect()->then(function (Client $client) {
  10. return $client->channel();
  11. })->then(function (Channel $channel) {
  12. return $channel->queueDeclare('hello', false, false, false, false)->then(function () use ($channel) {
  13. return $channel;
  14. });
  15. })->then(function (Channel $channel) {
  16. echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";
  17. $channel->consume(
  18. function (Message $message, Channel $channel, Client $client) {
  19. echo " [x] Received ", $message->content, "\n";
  20. },
  21. 'hello',
  22. '',
  23. false,
  24. true
  25. );
  26. });
  27. };
  28. Worker::runAll();

send.php

  1. <?php
  2. use Bunny\Channel;
  3. use Bunny\Message;
  4. use Workerman\Worker;
  5. use Workerman\RabbitMQ\Client;
  6. require __DIR__ . '/vendor/autoload.php';
  7. $worker = new Worker();
  8. $worker->onWorkerStart = function() {
  9. (new Client())->connect()->then(function (Client $client) {
  10. return $client->channel();
  11. })->then(function (Channel $channel) {
  12. return $channel->queueDeclare('hello', false, false, false, false)->then(function () use ($channel) {
  13. return $channel;
  14. });
  15. })->then(function (Channel $channel) {
  16. echo " [x] Sending 'Hello World!'\n";
  17. return $channel->publish('Hello World!', [], '', 'hello')->then(function () use ($channel) {
  18. return $channel;
  19. });
  20. })->then(function (Channel $channel) {
  21. echo " [x] Sent 'Hello World!'\n";
  22. $client = $channel->getClient();
  23. return $channel->close()->then(function () use ($client) {
  24. return $client;
  25. });
  26. })->then(function (Client $client) {
  27. $client->disconnect();
  28. });
  29. };
  30. Worker::runAll();