rabbitmq消息队列php实际应用

来源:互联网 发布:厦门软件企业 编辑:程序博客网 时间:2024/04/30 04:16

rabbitmq 消息队列 php应用

前段时间公司需要用到消息队列,就凑时间研究了下rabbitmq,由于本人ubuntu环境,windows应用不确定哈。

代码贴出来了,根据自身项目编写,并不适合所有项目,需要调整自行改动。


1.MQ则是遵循了AMQP协议的具体实现和产品,所以需要AMQPLib的支持

composer require php-amqplib/php-amqplib

2.参考

rabbitmq官方示例


3.base示例

<?phpnamespace 根据需要自定义;use PhpAmqpLib\Connection\AMQPStreamConnection;use PhpAmqpLib\Message\AMQPMessage;use 项目入口文件;class MqBase{    /**     * 配置     * @var type array     */    public $config = [];    /**     * 链接     * @var type object     */    public $channel, $connect;    /**     * 队列名称     * @var type string     */    public $queue_name = '';    /**     * @var type string     */    public $severity = '';    /**     * 路由名     * @var type string     */    public $exchange_name = '';    /**     *      * @param type $config     */    public function __construct($config = []) {        $this->config = [            'host' => 'localhost',            'port' => 5672,            'user' => 'guest',            'pwd'  => 'guest',            'vhost'=> '/',        ];        foreach(array_keys($this->config) as $key){            if(!empty($config[$key])){                $this->config[$key] = $config[$key];            }        }    }    /**     * 链接     * @param string $channel_id     * @return AMQPChannel     */    public function open($channel_id = null) {        $this->connect = new AMQPStreamConnection($this->config['host'], $this->config['port'], $this->config['user'], $this->config['pwd'], $this->config['vhost']);        $this->channel = $this->connect->channel($channel_id);    }    /**     * 队列     *      * @param string $queue     * @param bool $passive     * @param bool $durable     * @param bool $exclusive     * @param bool $auto_delete     * @param bool $nowait     * @param null $arguments     * @param null $ticket     * @return mixed|null     */    public function queueDeclare(        $queue = '',        $passive = false,        $durable = false,        $exclusive = false,        $auto_delete = false,        $nowait = false,        $arguments = null,        $ticket = null    ) {        $this->queue_name = $queue;        $this->channel->queue_declare($this->queue_name, $passive, $durable, $exclusive, $auto_delete, $nowait, $arguments, $ticket);    }    /**     * 队列绑定     * @param type $severity     */    public function queueBind($queue_name = '', $exchange_name = '', $severity = '') {        if($queue_name == '') $queue_name = $this->queue_name;        if($exchange_name == '') $exchange_name = $this->exchange_name;        $this->severity = $severity;        $this->channel->queue_bind($queue_name, $exchange_name, $this->severity);    }    /**     * 保存日志     * @param type $path 路径     * @param type $data 内容     * @param type $type mode     * @return type     */    public function putContents($path, $data = '', $type = '') {        return file_put_contents($path, $data, $type);    }    /**     * 发送     * @param type $names     */    /*public function send($names) {        $this->channel->queue_declare($names, false, false, false, false);    }*/    /**     * 路由     * @param type $exchange     * @param type $type     * @param type $durable     * @param type $passive     * @param type $auto_delete     * @param type $internal     * @param type $nowait     * @param type $arguments     * @param type $ticket     */    public function exchangeDeclare(        $exchange,        $type,        $durable = false,        $passive = false,        $auto_delete = true,        $internal = false,        $nowait = false,        $arguments = null,        $ticket = null    ) {        $this->exchange_name = $exchange;        $this->channel->exchange_declare($exchange, $type, $passive, $durable, $auto_delete, $internal, $nowait, $arguments, $ticket);    }    /**     * A Message for use with the Channnel.basic_* methods.     * @param type $msg     * @param type $message_durable     * @return type     */    public function message($msg, $message_durable) {        if($message_durable === true) {            return new AMQPMessage($msg, ['delivery_mode' => 2]);        }        return new AMQPMessage($msg);    }    /**     * 关闭队列和队列     */    public function close() {        $this->channel->close();        $this->connect->close();    }    /**     * Publishes a message     * 加入队列     * @param AMQPMessage $msg     * @param type $routing_key     * @param type $exchange     * @param type $mandatory     * @param type $immediate     * @param type $ticket     */    public function basicPublish(array $msg,        $message_durable = true,        $routing_key = '',        $exchange = '',        $mandatory = false,        $immediate = false,        $ticket = null    ) {        if(empty($msg['queue'])) {            $msg['queue'] = $this->queue_name;        }        if(is_array($msg)) {            $msg = serialize($msg);        }        if(!is_object($msg)) {            $msg = $this->message($msg, $message_durable);        }        $this->channel->basic_publish($msg, $exchange, $routing_key, $mandatory, $immediate, $ticket);    }    /**     *      * Wait for some expected AMQP methods and dispatch to them.     * Unexpected methods are queued up for later calls to this PHP     * method.     */    function wait(){        while(count($this->channel->callbacks)) {            $this->channel->wait();        }    }    /**     * start a queue consumer     * 开启手动处理消息状态     * @param type $consumer_tag     */    public function basicConsume($consumer_tag) {        $this->channel->basic_consume($this->queue_name, $consumer_tag);    }    /**     * acknowledge one or more messages     * 确认消息处理完成     * @param type $delivery_tag     */    public function basicAck($delivery_tag) {        $this->channel->basic_ack($delivery_tag);    }    /**     * 启动队列处理     *     * @param string $queue     * @param string $callback     * @param bool $consumer_tag     * @param bool $no_local     * @param bool $no_ack     * @param bool $exclusive     * @param callback|null $nowait     * @param int|null $ticket     * @param array $arguments     * @return mixed|string     */    function receive(        $queue = '',        $callback = null,        $consumer_tag = '',        $no_local = false,        $no_ack = false,        $exclusive = false,        $nowait = false,        $ticket = null,        $arguments = array()    ) {        $this->channel->basic_consume($queue, $consumer_tag, $no_local, $no_ack, $exclusive, $nowait, $callback, $ticket, $arguments);    }}

4.加入队列

use common\components\MqBase;
    /**     * 加入队列     * @param array $data         Description  队列数据        $data['time']不存在时只创建队列     * @param type $name          Description  队列名     * @param type $exchange_name Description  路由名     * @param type $queue_durable Description  队列是否持久化     * @param int $message_durableDescription  消息是否持久化     * @param type $config        Description  队列配置     * @throws Exception     */    public function send(array $data, $name, $exchange_name, $type = 'fanout', $queue_durable = true, $message_durable = true, $config = array()) {        $mqBase = new MqBase($config);        $mqBase->open();        $mqBase->exchangeDeclare($exchange_name, $type, $queue_durable);        $mqBase->queueDeclare($name, false, $queue_durable, false, false);        $mqBase->basicPublish($data, $message_durable, $name);    }

5.处理示例

    /**     * 处理队列     * 可根据项目自行调整     * @param type $name 队列名     */    public function actionIndex($name, $exchange_name) {        $mqBase = new MqBase();        $mqBase->open();        $mqBase->queueDeclare($name, false, true, false, false);        if($exchange_name == '') {            $exchange_name = $name;        }        $mqBase->queueBind($name, $exchange_name);        $callback = function($msg) {            $data = unserialize($msg->body);            $func = $data['func'];            $class = $data['class'];            if(isset($data['time']) && $data['time'] <= time()) {                if(is_object($data['class'])) {                    $log = $class->$func($data['paramer']);                } else {                    $log = $class::$func($data['paramer']);                }                if($log === true) {                    $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);                }            }        };        $mqBase->receive($name, $callback);        $mqBase->wait();    }}
0 0