一個簡單的 Amqp 封裝

李銘昕發表於2018-11-24

先說一下,為什麼會實現這麼一個擴充套件吧。平常使用PHP寫東西,都是獨立專案,所以我們可能只需要一個redis-list-queue,來實現訊息佇列。但當你專案間需要互動時,redis list 顯然已經不滿足條件了。這個時候,我們可以使用swoole實現一個簡單的RPC元件,但是有時候我們還是必須要使用訊息佇列的訂閱釋出功能。所以,我在swoft/php-amqplib的基礎上封裝了這個元件。

一個簡單的Amqp封裝

使用

使用上十分簡單,首先我們定義一個Connection類。

use yii\base\StaticInstanceTrait;
class YiiConnection extends \Swoftx\Amqplib\Connection
{
    use StaticInstanceTrait;
}

然後便是我們的訊息類

use yii\base\StaticInstanceTrait;
use Swoftx\Amqplib\Connection;
use Swoftx\Amqplib\Message\Publisher;
use YiiConnection;

class DemoMessage extends Publisher
{
    protected $exchange = 'demo';

    protected $routingKey = 'test';

    public function getConnection(): Connection
    {
        return YiiConnection::instance()->build();
    }
}

接下來就是傳送訊息

use DemoMessage;

$msg = new DemoMessage();
$msg->setData(['id' => $id]);
$msg->publish();

DemoMessage::make()->setData(['id'=>$id])->publish();

是不是相比下面的一坨程式碼,清爽很多呢??

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$exchange = 'router';
$queue = 'msgs';
$connection = new AMQPStreamConnection(HOST, PORT, USER, PASS, VHOST);
$channel = $connection->channel();
/*
    The following code is the same both in the consumer and the producer.
    In this way we are sure we always have a queue to consume from and an
        exchange where to publish messages.
*/
/*
    name: $queue
    passive: false
    durable: true // the queue will survive server restarts
    exclusive: false // the queue can be accessed in other channels
    auto_delete: false //the queue won't be deleted once the channel is closed.
*/
$channel->queue_declare($queue, false, true, false, false);
/*
    name: $exchange
    type: direct
    passive: false
    durable: true // the exchange will survive server restarts
    auto_delete: false //the exchange won't be deleted once the channel is closed.
*/
$channel->exchange_declare($exchange, 'direct', false, true, false);
$channel->queue_bind($queue, $exchange);
$messageBody = implode(' ', array_slice($argv, 1));
$message = new AMQPMessage($messageBody, array('content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
$channel->basic_publish($message, $exchange);
$channel->close();
$connection->close();
本作品採用《CC 協議》,轉載必須註明作者和本文連結

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

相關文章