1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CentOSでRabbitMQ+PHPを試す

Posted at

PHPで非同期処理を導入するために、RabbitMQを試した際のメモ。
※この記事ではCentOS7、PHP7.3を使用しています。

MQの準備

RabbitMQインストール

yum --enablerepo=epel -y install rabbitmq-server
systemctl start rabbitmq-server
systemctl enable rabbitmq-server

ユーザ追加

rabbitmqctl add_user mquser password
rabbitmqctl list_users

バーチャルホスト追加

rabbitmqctl add_vhost myhost
rabbitmqctl list_vhosts

パーミッション設定

rabbitmqctl set_permissions -p myhost mquser ".*" ".*" ".*"
rabbitmqctl list_permissions -p myhost

PHPプログラムの準備(送信側&受信側)

phpライブラリインストール

yum -y install --enablerepo=epel,remi-php73 php php-bcmath composer

composerインストール

※一般ユーザにて実施

cd
mkdir mq
cd mq
composer require php-amqplib/php-amqplib
composer install

送信側

送信アプリ作成

vi send_msg.php
<?php
require_once __DIR__ . '/vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$connection = new AMQPStreamConnection('127.0.0.1', 5672, 'mquser', 'password', 'myhost');

$channel = $connection->channel();
$channel->queue_declare('Hello_World', false, false, false, false);

$msg = new AMQPMessage('Hello RabbitMQ World!');
$channel->basic_publish($msg, '', 'Hello_World');
echo " [x] Sent 'Hello_World'\n";

$channel->close();
$connection->close();
?>

送信

php send_msg.php

受信側

受信アプリ作成

vi receive_msg.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection('127.0.0.1', 5672, 'mquser', 'password', 'myhost');
$channel = $connection->channel();

$channel->queue_declare('Hello_World', false, false, false, false);

echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

$callback = function($msg) {
    echo " [x] Received ", $msg->body, "\n";
};

$channel->basic_consume('Hello_World', '', false, true, false, false, $callback);

while(count($channel->callbacks)) {
    $channel->wait();
}
?>

受信

php receive_msg.php
(CTRL+Cで停止)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?