PHP + RabbitMQ implements message queuing (full code)

Time:2019-5-30
  • Preface

    Firstly, install the RabbitMQ corresponding to PHP. There will be slight differences in different extension implementations of php_amqp.
    PHP extension address: http://pecl.php.net/package/amqp
    Specific quasi-official website http://www.rabbitmq.com/getstarted.html
  • introduce

    Configuration information for config.php
    BaseMQ.php MQ base class
    ProductMQ.php Producer Class
    ConsumerMQ.php Consumer Class
    Consumer2MQ. PHP Consumer2 (there may be multiple)
  • config.php
<?php
    return [
        // configuration
        'host' => [
            'host' => '127.0.0.1',
            'port' => '5672',
            'login' => 'guest',
            'password' => 'guest',
            'vhost'=>'/',
        ],
        // switch
        'exchange'=>'word',
        // routing
        'routes' => [],
    ];
  • BaseMQ.php
    <?php
    /**
     * Created by PhpStorm.
     * User: pc
     * Date: 2018/12/13
     * Time: 14:11
     */
    
    namespace MyObjSummary\rabbitMQ;
    
    /** Member
     *      AMQPChannel
     *      AMQPConnection
     *      AMQPEnvelope
     *      AMQPExchange
     *      AMQPQueue
     * Class BaseMQ
     * @package MyObjSummary\rabbitMQ
     */
    class BaseMQ
    {
        /** MQ Channel
         * @var \AMQPChannel
         */
        public $AMQPChannel ;
    
        /** MQ Link
         * @var \AMQPConnection
         */
        public $AMQPConnection ;
    
        /** MQ Envelope
         * @var \AMQPEnvelope
         */
        public $AMQPEnvelope ;
    
        /** MQ Exchange
         * @var \AMQPExchange
         */
        public $AMQPExchange ;
    
        /** MQ Queue
         * @var \AMQPQueue
         */
        public $AMQPQueue ;
    
        /** conf
         * @var
         */
        public $conf ;
    
        /** exchange
         * @var
         */
        public $exchange ;
    
        /** link
         * BaseMQ constructor.
         * @throws \AMQPConnectionException
         */
        public function __construct()
        {
            $conf =  require 'config.php' ;
            if(!$conf)
                throw new \AMQPConnectionException('config error!');
            $this->conf     = $conf['host'] ;
            $this->exchange = $conf['exchange'] ;
            $this->AMQPConnection = new \AMQPConnection($this->conf);
            if (!$this->AMQPConnection->connect())
                throw new \AMQPConnectionException("Cannot connect to the broker!\n");
        }
    
        /**
         * close link
         */
        public function close()
        {
            $this->AMQPConnection->disconnect();
        }
    
        /** Channel
         * @return \AMQPChannel
         * @throws \AMQPConnectionException
         */
        public function channel()
        {
            if(!$this->AMQPChannel) {
                $this->AMQPChannel =  new \AMQPChannel($this->AMQPConnection);
            }
            return $this->AMQPChannel;
        }
    
        /** Exchange
         * @return \AMQPExchange
         * @throws \AMQPConnectionException
         * @throws \AMQPExchangeException
         */
        public function exchange()
        {
            if(!$this->AMQPExchange) {
                $this->AMQPExchange = new \AMQPExchange($this->channel());
                $this->AMQPExchange->setName($this->exchange);
            }
            return $this->AMQPExchange ;
        }
    
        /** queue
         * @return \AMQPQueue
         * @throws \AMQPConnectionException
         * @throws \AMQPQueueException
         */
        public function queue()
        {
            if(!$this->AMQPQueue) {
                $this->AMQPQueue = new \AMQPQueue($this->channel());
            }
            return $this->AMQPQueue ;
        }
    
        /** Envelope
         * @return \AMQPEnvelope
         */
        public function envelope()
        {
            if(!$this->AMQPEnvelope) {
                $this->AMQPEnvelope = new \AMQPEnvelope();
            }
            return $this->AMQPEnvelope;
        }
    }
  • ProductMQ.php
<?php
    // Producer P
    namespace MyObjSummary\rabbitMQ;
    require 'BaseMQ.php';
    class ProductMQ extends BaseMQ
    {
        Private $routes = ['hello','word']; // routing key
    
        /**
         * ProductMQ constructor.
         * @throws \AMQPConnectionException
         */
        public function __construct()
        {
           parent::__construct();
        }
    
        / ** Controls only the success of the delivery and does not accept whether the consumer receives it or not.
         * @throws \AMQPChannelException
         * @throws \AMQPConnectionException
         * @throws \AMQPExchangeException
         */
        public function run()
        {
            // Channel
            $channel = $this->channel();
            // Creating Switch Objects
            $ex = $this->exchange();
            // Message content
            $message = 'product message '.rand(1,99999);
            // Start a business
            $channel->startTransaction();
            $sendEd = true ;
            foreach ($this->routes as $route) {
                $sendEd = $ex->publish($message, $route) ;
                echo "Send Message:".$sendEd."\n";
            }
            if(!$sendEd) {
                $channel->rollbackTransaction();
            }
            $channel - > commitTransaction ();//commit transaction
            $this->close();
            die ;
        }
    }
    try{
        (new ProductMQ())->run();
    }catch (\Exception $exception){
        var_dump($exception->getMessage()) ;
    }
  • ConsumerMQ.php
<?php
    // Consumer C
    namespace MyObjSummary\rabbitMQ;
    require 'BaseMQ.php';
    class ConsumerMQ extends BaseMQ
    {
        Private $q_name ='hello'; // queue name
        Private $route ='hello'; // routing key
    
        /**
         * ConsumerMQ constructor.
         * @throws \AMQPConnectionException
         */
        public function __construct()
        {
            parent::__construct();
        }
    
        / ** Accept a message if it terminates reconnection
         * @throws \AMQPChannelException
         * @throws \AMQPConnectionException
         * @throws \AMQPExchangeException
         * @throws \AMQPQueueException
         */
        public function run()
        {
    
            // Create a switch
            $ex = $this->exchange();
            $ex - > setType (AMQP_EX_TYPE_DIRECT); //direct type
            $ex - > setFlags (AMQP_DURABLE); //persistence
            //echo "Exchange Status:".$ex->declare()."\n";
    
            // Create queues
            $q = $this->queue();
            //var_dump($q->declare());exit();
            $q->setName($this->q_name);
            $q - > setFlags (AMQP_DURABLE); // Persistence
            //echo "Message Total:".$q->declareQueue()."\n";
    
            // Bind switches to queues and specify routing keys
            echo 'Queue Bind: '.$q->bind($this->exchange, $this->route)."\n";
    
            // Blocking mode receives messages
            echo "Message:\n";
            while(True){
                $q->consume(function ($envelope,$queue){
                    $msg = $envelope->getBody();
                    Echo $msg. " n";//Processing messages
                    $queue - > ACK ($envelope - > getDelivery Tag ();// Send ACK response manually
                });
                // $q - > consume ('processMessage', AMQP_AUTOACK); //automatic ACK response
            }
            $this->close();
        }
    }
    try{
        (new ConsumerMQ)->run();
    }catch (\Exception $exception){
        var_dump($exception->getMessage()) ;
    }

Recommended Today

The basic syntax and function of triggers in SQLSEVER

What is a trigger? Triggers are stored procedures that are executed automatically when a table is inserted, updated, or deleted. A special stored procedure that is automatically executed when a trigger inserts, updates, or deletes a table. Triggers are generally used for more complex check constraints. The difference between a trigger and a normal stored […]