PHP integrates rabbitmq records

1. Configuration

Overall reference https://www.cnblogs.com/miketwais/p/RabbitMQ.html

Downloading from http://pecl.php.net/package/amqp is to note that only the version before 1.4 supports php5, while the php under xmapp is 5.6. Also note that the php version of xmapp is x86, and the thread-safe version is selected as follows picture


Choose the last one, and there is generally no problem with choosing the right version. If there is a problem, php -v will generally report an error.


2. Download the third-party library with composer under tp5

The composer.json file under tp5 is added

"require": {
        "php": ">=5.4.0",
        "topthink/think-installer": "~1.0",
        "php-amqplib/php-amqplib": "^2.7"

    },

Or composer require php-amqplib/php-amqplib directly in the corresponding directory 

After waiting for a while, you can see the downloaded file in the vendor directory and you can use it (note that composer.json must be in the root directory of the directory)


3. Code testing

tp5 supports composer's autoload so use it directly

use PhpAmqpLib\Connection\AMQPStreamConnection;

use PhpAmqpLib\Message\AMQPMessage;


$conn_args = array(
            'host' => '127.0.0.1',
            'port' => '5672',
            'login' => 'test',
            'password' => '123456',
            'vhost'=>'/'
        );
        $e_name = 'KSHOP'; //交换机名

        $k_queue = 'hello'; //路由key





 $connection = new AMQPStreamConnection($conn_args['host'], $conn_args['port'], $conn_args['login'],    $conn_args['password'], $conn_args['vhost']); // 创建连接
        $channel = $connection->channel();
        $channel->queue_declare($k_queue, false, true, false, false);
        $channel->exchange_declare($e_name, 'direct', false, true, false);
        $channel->queue_bind($k_queue, $e_name); // queue and exchange binding
        $messageBody = 'testinfo12'; // 要推送的消息
   $message = new AMQPMessage($messageBody, array('content_type' => 'text/plain', 'delivery_mode' =>                AMQPMessage::DELIVERY_MODE_PERSISTENT));
        $channel->basic_publish($message, '',$k_queue); // 推送消息
        $channel->close();

        $connection->close();



4. Test the effect

After running the code, the java running code receives the message, and the background message queue based on rabbitmq is basically integrated.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325954595&siteId=291194637