• RabbitMq初探——Hello World


    HelloWorld

    前言


    这里我们弱化broker内部构造。将整体分为三部分。

    P:producer。生产者。

    C:Consumer。消费者。

    queue:队列。

    后面的代码都依赖于 the php-amqplib API

    composer安装php-amqplib 


    1. 新建composer.json

    {
        "require": {
            "php-amqplib/php-amqplib": ">=2.6.1"
        }
    }

     2. composer.phar install 

    Hello World


    talk is cheap , show you the code

    sender.php

    require_once __DIR__ . '/vendor/autoload.php';
    use PhpAmqpLibConnectionAMQPStreamConnection;
    use PhpAmqpLibMessageAMQPMessage;
    
    $connection = new AMQPStreamConnection('127.0.0.1', 5672, 'guest', 'guest');
    $channel = $connection->channel();
    
    
    $channel->queue_declare('hello', false, false, false, false);
    
    $data = implode(" ", array_slice($argv, 1));
    empty($data) && $data = "Hello World!";
    
    $msg = new AMQPMessage($data);
    
    $channel->basic_publish($msg, '', 'hello');
    
    echo " [x] Sent '$data'
    ";
    
    //close the channel and connection;
    $channel->close();
    $connection->close();

    receive.php

    require_once __DIR__ . '/vendor/autoload.php';
    use PhpAmqpLibConnectionAMQPStreamConnection;
    
    $connection = new AMQPStreamConnection('127.0.0.1', 5672, 'guest', 'guest');
    $channel = $connection->channel();
    
    $channel->queue_declare('hello', false, false, false, false);
    echo ' [*] Waiting for messages. To exit press CTRL+C', "
    ";
    
    $callback = function($msg) {
        echo "[x] Received ", $msg->body, "
    ";
        sleep(substr_count($msg->body, '.'));
        echo "[x] Done
    ";
    };
    $channel->basic_consume('hello', '', false, true, false, false, $callback);
    
    while(count($channel->callbacks)) {
        $channel->wait();
    }

    执行

    打开两个终端,分别执行两个脚本。

    终端一:

    终端二:

    终端一收到终端二发送的消息。

  • 相关阅读:
    数据结构与算法之美-二分查找(下)
    数据结构与算法之美-二分查找(上)
    数据结构与算法之美-排序优化
    数据结构与算法之美-线性排序
    DRF框架之路由Routers
    DRF框架之视图集(ModelViewSet)简介
    DRF框架之视图子类简介
    DRF框架之视图的扩展类简介
    DRF框架之视图基类APIView和GenericAPIView简介
    DRF框架之ModelSerializer序列化器
  • 原文地址:https://www.cnblogs.com/hejun695/p/7687380.html
Copyright © 2020-2023  润新知