zoukankan      html  css  js  c++  java
  • php如何使用rabbitmq实现发布消息和消费消息(tp框架)(第一篇)

    1,默认已经安装好了rabbitmq: 参考 http://www.cnblogs.com/spicy/p/7017603.html

    2,安装rabbitmq客户端: 方法1: pecl 扩展安装  方法2:composer安装

      我是用第二种: composer require php-amqplib/php-amqplib 

    3,新建一个发送的路由 和 接受的路由(tp5)

      Route::rule('test','index/index/test1');

      Route::rule('getmsg','index/receiver/receive');

    4,发布信息的方法:
      
    <?php
    namespace appindexcontroller;
    
    use PhpAmqpLibConnectionAMQPStreamConnection;
    use PhpAmqpLibMessageAMQPMessage;
    use validatorValidator;
    
    class Index
    {
        //rbmp example
        public function test1()
        {
            $connection = new AMQPStreamConnection('localhost', 5672, 'bitch', 'bitch');
            $channel = $connection->channel();
            $channel->queue_declare('hello', false, true);
    
            $sendMsg = [
                'name'=>'kevin'.rand(1,100),
                'phone'=>'171921743'.rand(1,100),
            ];
    
            $msg = new AMQPMessage(json_encode($sendMsg));
            $channel->basic_publish($msg, '', 'hello');
            echo " [x] Sent 'Hello Kevin!'
    ";
            $channel->close();
            $connection->close();
        }
    View Code

     5,消费信息的方法:

      

    <?php
    namespace appindexcontroller;
    
    use PhpAmqpLibConnectionAMQPStreamConnection;
    
    class Receiver
    {
        public function receive()
        {
            set_time_limit(0);
            $connection = new AMQPStreamConnection('localhost', 5672, 'bitch', 'bitch');
            $channel = $connection->channel();
            $channel->queue_declare('hello', false, true);
    
            $receiver = new self();
            $channel->basic_consume('hello', '', false, true, false, false, [$receiver, 'callFunc']);
    
            while(true) {
                $channel->wait();
            }
            $channel->close();
            $connection->close();
        }
    
        public function callFunc($msg) {
            $content = json_decode($msg->body,true);
            
            //把用户信息插入数据库
            db('user_info')->insert([
                'ui_username'=>$content['name'],
                'ui_phone'=>$content['phone'],
            ]);
            
    
        }
    
    }
    View Code

    注意:  我们公司是把消费消息做成了常驻  



      

     

  • 相关阅读:
    C语言判断函数
    从函数调用来思考多态
    C语言读取每一行文本
    任务栏上的资源管理器图标,没有jump list?其他都有。
    The specified child already has a parent错误
    SQL语句的添加、删除、修改多种方法
    菜鸟开技术博啦
    若不能连接到sql server的localhost
    微软Live Mail包含重大Bug,可导致用户无法登录,我已经一个多月无法登录自己的邮箱了。 无为而为
    试试Communicator Web Access 中文版 无为而为
  • 原文地址:https://www.cnblogs.com/spicy/p/7886820.html
Copyright © 2011-2022 走看看