zoukankan      html  css  js  c++  java
  • yii2用php-amqplib使用rabbitmq

    1.将php-amqplib拷贝至yii2项目,新建phpclient类  

    <?php
    use PhpAmqpLibConnectionAMQPStreamConnection;
    use PhpAmqpLibMessageAMQPMessage;
    
    class PhpClient
    {
       public static function Call($n){
           require_once __DIR__ . '/vendor/autoload.php';
    
           $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
           $channel = $connection->channel();
    
           $channel->queue_declare('task_queue', false, true, false, false);
    
           $data=empty($n)?"Hello World!":$n;
    
           $msg = new AMQPMessage($data,
               array('delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT)
           );
    
           $channel->basic_publish($msg, '', 'task_queue');
    
           $channel->close();
           $connection->close();
    
           return true;
       }
    }

    2.commands中新建controller简单实现tasker和worker

    <?php
    namespace appcommands;
    
    use yiiconsoleController;
    use Yii;
    use PhpAmqpLibConnectionAMQPStreamConnection;
    
    class RabbittaskController extends Controller
    {
        public function actionWorker()
        {
            require(Yii::getAlias('@vendor') . '/rabbitmq/vendor/autoload.php');
    
            $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
            $channel = $connection->channel();
    
            $channel->queue_declare('task_queue', false, true, false, false);
    
            $callback = function ($msg) {
           //$msg->body
                //do sth
    
                $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
            };
    
            $channel->basic_qos(null, 1, null);
            $channel->basic_consume('task_queue', '', false, false, false, false, $callback);
    
            while (count($channel->callbacks)) {
                $channel->wait();
            }
    
            $channel->close();
            $connection->close();
        }
    
        public function actionNewTask()
        {
            require(Yii::getAlias('@vendor') . '/rabbitmq/PhpClient.php');
            PhpClient::Call('test!');
        }
    }
  • 相关阅读:
    mfc crc校验工具
    MFC 配置附加目录
    多线程中如何使用gdb精确定位死锁问题
    符号冲突
    动态库之间单例模式出现多个实例(Linux)
    c++普通函数在头文件定义报重复定义的错误。而class定义不会
    static初始化顺序及延伸
    tcmalloc使用中出现崩溃问题记录
    shell脚本—判断***是否安装
    【1080TI驱动+CUDA10.1+cudnn】安装记录
  • 原文地址:https://www.cnblogs.com/luotingliang/p/7267253.html
Copyright © 2011-2022 走看看