国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Introduction to message queue and message queue application scenarios
RabbitMQ
rabbitmq installation startup
simple模式消費(fèi)者接受消息
worker模式生產(chǎn)消費(fèi)消息
fanout模式生產(chǎn)者推送到交換器
direct模式消息隊(duì)列使用
topic模式消息隊(duì)列使用
Home Backend Development PHP Tutorial Getting started with message queue RabbitMQ and detailed explanation of PHP examples

Getting started with message queue RabbitMQ and detailed explanation of PHP examples

May 12, 2022 pm 06:33 PM
php

This article brings you relevant knowledge about PHP, which mainly introduces the introduction of message queue RabbitMQ and some practical details. The message queue is a communication method between applications. Let’s talk about it together. Take a look, hope it helps everyone.

Getting started with message queue RabbitMQ and detailed explanation of PHP examples

Recommended study: "PHP Video Tutorial"

Introduction to message queue and message queue application scenarios

RabbitMQ

Description
MQ (Message Queue) is a message queue, which is a communication method between applications. The message can be returned immediately after it is sent. , the message system ensures reliable delivery of messages. "Message queue" is a container that saves messages during their transmission. It is typical: producer, consumer model. Producers continue to produce messages into the message queue, and consumers continue to obtain messages from the queue. Because the production and consumption of messages are asynchronous, and only care about the sending and receiving of messages, there is no intrusion of business logic, thus achieving the decoupling of producers and consumers.

Why use message middleware?
The message queue is an important component in the distributed system. It solves problems such as application decoupling, asynchronous messaging, and traffic peak shaving, and achieves high concurrency, high availability, scalability, and eventual consistency architecture

Asynchronous processing
Users need to send emails and registration text messages after registering information
1. After the user registration information is written into the database, even if the registration is successful, information about successful registration is returned
2. Sending emails and registration text messages Executed asynchronously through the message queue, the user does not need to wait for these two operations
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

#Application decoupling
After the user places an order, the order system needs to notify the inventory system. The traditional approach is that the order system calls the interface of the inventory system to increase or decrease inventory
1. The user places an order for production and returns a success prompt
2. The queue consumption inventory system increases or decreases inventory
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

Traffic peak shaving
Traffic peak shaving is also a common scenario in message queues. It is generally used extensively in flash sales or group grab activities
1. When a group of users Requests come and enter the queue, and the number of queues is controlled. If the number exceeds a certain number, the flash sale will end.
2. Then the queues will be consumed one by one according to the first-in-first-out method
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

Rabbitmq Features

Reliability RabbitMQ uses some mechanisms to ensure reliability, such as persistence, transmission confirmation, and release confirmation.
Flexible Routing The message is routed through Exchange before the message enters the queue. For typical routing functionality, RabbitMQ already provides some built-in Exchange implementations. For more complex routing functions, multiple Exchanges can be bound together, and your own Exchange can also be implemented through the plug-in mechanism.
Message Clustering Multiple RabbitMQ servers can form a cluster to form a logical Broker.
Highly Available Queues Queues can be mirrored on machines in the cluster, so that the queues are still available if some nodes have problems.
Multi-protocol RabbitMQ supports multiple message queue protocols, such as STOMP, MQTT, etc.
Multi-language clients (Many Clients) RabbitMQ supports almost all commonly used languages, such as PHP Java, .NET, Ruby, etc.
Management UI (Management UI) RabbitMQ provides an easy-to-use user interface that allows users to monitor and manage many aspects of the message Broker.
Tracing mechanism (Tracing) If the message is abnormal, RabbitMQ provides a message tracking mechanism so that users can find out what happened.
Plugin System RabbitMQ provides many plug-ins to expand in many aspects, and you can also write your own plug-ins.

How RabbitMQ works
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

Broker: An application that receives and distributes messages, RabbitMQ Server is the Message Broker.

Virtual host: Similar to mysql database, when multiple different users use the services provided by the same RabbitMQ server, multiple vhosts can be divided, and each user can use the service provided by the same RabbitMQ server. vhost creates exchange/queue, etc.

Connection: TCP connection between publisher/consumer and broker.

Channel: If a Connection is established every time RabbitMQ is accessed, the overhead of establishing a TCP Connection will be huge and the efficiency will be low when the message volume is large. Channel is a logical connection established inside the connection. As a lightweight Connection, Channel greatly reduces the cost of establishing a TCP connection by the operating system.

Exchange: The message reaches the first stop of the broker. According to the distribution rules, it matches the routing key in the query table and distributes the message to the queue. Commonly used types are: direct (point-to-point), topic (publish-subscribe) and fanout (multicast).

Queue: The message is finally sent here to be picked up by the consumer. A message can be copied to multiple queues at the same time.

rabbitmq installation startup

RabbitMQ official address: http://www.rabbitmq.com
To install rabbitmq, you need to install erlang first

The first step: Erlang installation
To install rabbitmq, you need to install erlang first. Centos7 does not support the installation of erlang 24 version
Getting started with message queue RabbitMQ and detailed explanation of PHP examples
Download:
Getting started with message queue RabbitMQ and detailed explanation of PHP examples
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

Getting started with message queue RabbitMQ and detailed explanation of PHP examples

Getting started with message queue RabbitMQ and detailed explanation of PHP examples
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

Getting started with message queue RabbitMQ and detailed explanation of PHP examples##

#?系統(tǒng)??centos?7#?下載erlang包,手動(dòng)下載后上傳至服務(wù)器,我在使用wget下載后無法安裝,這里沒明白


#?安裝
yum?install?erlang-23.3.4.4-1.el7.x86_64.rpm

#?驗(yàn)證安裝是否成功
erl

Getting started with message queue RabbitMQ and detailed explanation of PHP examples

Second Step: Install rabbitmq
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

Getting started with message queue RabbitMQ and detailed explanation of PHP examples
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

#?系統(tǒng)??centos?7#?下載rabbitmq包,手動(dòng)下載后上傳至服務(wù)器,我在使用wget下載后無法安裝,這里沒明白


#?安裝
yum?install?rabbitmq-server-3.8.19-1.el7.noarch.rpm?

#?啟動(dòng)
systemctl?start?rabbitmq-server

#?關(guān)閉
systemctl?stop?rabbitmq-server

#?查看默認(rèn)端口服務(wù)是否啟動(dòng)
netstat?-tunlp

Getting started with message queue RabbitMQ and detailed explanation of PHP examples

php message queue rabbitmq various Mode usage

rabbitmq management interface and command line usage

4369: epmd (Erlang Port Mapper Daemon), erlang service port

5672: client communication port

15672: HTTP API client, management UI (only if management plugin is enabled) does not necessarily start

25672: Used for inter-node communication (Erlang distribution server port)

rabbitmq Management Command Start 15672: HTTP API client, management UI (only when the management plug-in is enabled)

#?啟動(dòng)rabbitmq_management插件
rabbitmq-plugins??enable??rabbitmq_management

#?查看所有插件
rabbitmq-plugins??list
Test access to the UI interface: (not at this time The localhost address cannot be logged in)

http://192.168.10.105:15672/

rabbitmq configuration management interface

#?新增一個(gè)用戶??
rabbitmqctl?add_user?【用戶名Username】?【密碼Password】
rabbitmqctl?add_user?root?root
#?刪除一個(gè)用戶??
rabbitmqctl?delete_user?Username

#?修改用戶的密碼?
rabbitmqctl?change_password?Username?Newpassword?

#?查看當(dāng)前用戶列表????
rabbitmqctl?list_users

#?設(shè)置用戶角色的命令為:?
rabbitmqctl?set_user_tags?User?Tag??
rabbitmqctl?set_user_tags?root?administrator
#?User為用戶名,?Tag為角色名(對(duì)應(yīng)于上面的administrator,monitoring,policymaker,management,或其他自定義名稱)。

Command line to create vhost and PHP extension installation Similar to mysql database, when multiple different users use the services provided by the same RabbitMQ server, multiple vhosts can be divided, and each user creates exchange/queue, etc. in their own vhost. .

1) View vhosts of different users


Getting started with message queue RabbitMQ and detailed explanation of PHP examples
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

Create vhost and assign permissions

#?新增vhost
rabbitmqctl?add_vhost???vhostname
rabbitmqctl?add_vhost?order

#?查看vhost列表
rabbitmqctl??list_vhosts

#為vhost添加用戶
rabbitmqctl?set_permissions?-p?vhostname?username?".*"?".*"?".*"rabbitmqctl?set_permissions?-p?order?root?".*"?".*"?".*"
?".*"?".*"?".*"后邊三個(gè).*分別代表:配置權(quán)限、寫權(quán)限、讀權(quán)限

Getting started with message queue RabbitMQ and detailed explanation of PHP examples

2) Install rabbitmq extension installation for php

https://github.com/php-amqplib/php-amqplib Extension installation

Modify Alibaba Cloud Image

composer?config?-g?repo.packagist?composer?https://mirrors.aliyun.com/composer/
Start downloading – Sometimes the lower version of 2.8 will be downloaded here. You need to specify the version

. If the download is unsuccessful, upgrade composer, php.ini, open sockets, expand and switch domestic mirrors

Getting started with message queue RabbitMQ and detailed explanation of PHP examples

#?升級(jí)composer
composer?self-update

#php.ini?打開?sockets?擴(kuò)展

#下載指定版本
composer?require?php-amqplib/php-amqplib=^3.0

Simple mode producer messages are pushed to the message queue Documentation:
https://www.rabbitmq.com/tutorials/tutorial-one-php.html

Simple producer and messager


Getting started with message queue RabbitMQ and detailed explanation of PHP examples Producer code
http://localhost/rabbitmq/simple/pro.php

<?php require_once "../vendor/autoload.php";

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

//生產(chǎn)者
//Connection: publisher/consumer和broker之間的TCP連接
//Channel: 如果每一次訪問RabbitMQ都建立一個(gè)Connection,在消息量大的時(shí)候建立TCP Connection的開銷將是巨大的,效率也較低。Channel是在connection內(nèi)部建立的邏輯連接Channel作為輕量級(jí)的Connection極大減少了操作系統(tǒng)建立TCP connection的開銷。

//建立connction
$connection = new AMQPStreamConnection(&#39;192.168.10.105&#39;, 5672, &#39;root&#39;, &#39;root&#39;, &#39;order&#39;);
//Channel
$channel = $connection->channel();
//聲明隊(duì)列名為:goods
$queue_name?=?'goods';
$channel->queue_declare($queue_name,?false,?true,?false,?false);

//生產(chǎn)數(shù)據(jù)
$data?=?'this?is?messge';
//創(chuàng)建消息
$msg?=?new?AMQPMessage($data,?['delivery_mode'?=>?AMQPMessage::DELIVERY_MODE_NON_PERSISTENT]);
//發(fā)布消息
$channel->basic_publish($msg,?$exchange?=?'',?$queue_name);
//關(guān)閉連接
$channel->close();
$connection->close();

運(yùn)行生產(chǎn)者腳本:
http://localhost/rabbitmq/simple/pro.php
Getting started with message queue RabbitMQ and detailed explanation of PHP examples
點(diǎn)擊goods隊(duì)列可以進(jìn)入到消息詳情
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

simple模式消費(fèi)者接受消息

http://localhost/rabbitmq/simple/con.php

<?php require_once "../vendor/autoload.php";

use PhpAmqpLib\Connection\AMQPStreamConnection;

//建立connction
$connection = new AMQPStreamConnection(&#39;192.168.10.105&#39;, 5672, &#39;root&#39;, &#39;root&#39;, &#39;order&#39;);
//Channel
$channel = $connection->channel();

//聲明隊(duì)列名為:goods
$queue_name?=?'goods';
$channel->queue_declare($queue_name,?false,?true,?false,?false);

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

$callback?=?function?($msg)?{
????echo?'received?=?',?$msg->body?.?"\n";
};
//開啟消費(fèi)
$channel->basic_consume($queue_name,?'',?false,?true,?false,?false,?$callback);

//不斷的循環(huán)進(jìn)行消費(fèi)
while?($channel->is_open())?{
????$channel->wait();
}

//關(guān)閉連接
$channel->close();
$connection->close();

worker模式生產(chǎn)消費(fèi)消息

rabbitmq Work Queues
一個(gè)生產(chǎn)者對(duì)應(yīng)多個(gè)消費(fèi)者,消費(fèi)特別慢時(shí)增加幾個(gè)消費(fèi)分發(fā)
Getting started with message queue RabbitMQ and detailed explanation of PHP examples
生產(chǎn)者,和上文生產(chǎn)者不變

<?php require_once "../vendor/autoload.php";

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

//生產(chǎn)者
//Connection: publisher/consumer和broker之間的TCP連接
//Channel: 如果每一次訪問RabbitMQ都建立一個(gè)Connection,在消息量大的時(shí)候建立TCP Connection的開銷將是巨大的,效率也較低。Channel是在connection內(nèi)部建立的邏輯連接Channel作為輕量級(jí)的Connection極大減少了操作系統(tǒng)建立TCP connection的開銷。

//建立connction
$connection = new AMQPStreamConnection(&#39;192.168.10.105&#39;, 5672, &#39;root&#39;, &#39;root&#39;, &#39;order&#39;);
//Channel
$channel = $connection->channel();
//聲明隊(duì)列名為:task_queue
$queue_name?=?'task_queue';
$channel->queue_declare($queue_name,?false,?true,?false,?false);

for?($i?=?0;?$i??AMQPMessage::DELIVERY_MODE_NON_PERSISTENT]);
//發(fā)布消息
????$channel->basic_publish($msg,?$exchange?=?'',?$queue_name);
}

//關(guān)閉連接
$channel->close();
$connection->close();

消費(fèi)者worker1
D:\phpstudy_pro\WWW\rabbitmq\worker\worker1.php

<?php require_once "../vendor/autoload.php";

use PhpAmqpLib\Connection\AMQPStreamConnection;

//建立connction
$connection = new AMQPStreamConnection(&#39;192.168.10.105&#39;, 5672, &#39;root&#39;, &#39;root&#39;, &#39;order&#39;);
//Channel
$channel = $connection->channel();

//聲明隊(duì)列名為:task_queue
$queue_name?=?'task_queue';
$channel->queue_declare($queue_name,?false,?true,?false,?false);

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

$callback?=?function?($msg)?{
????echo?'received?=?',?$msg->body?.?"\n";
};
//開啟消費(fèi)
$channel->basic_consume($queue_name,?'',?false,?true,?false,?false,?$callback);

//不斷的循環(huán)進(jìn)行消費(fèi)
while?($channel->is_open())?{
????$channel->wait();
}

//關(guān)閉連接
$channel->close();
$connection->close();

消費(fèi)者worker2,代碼和worker1一樣,同時(shí)運(yùn)行開啟后會(huì)一起消費(fèi)
D:\phpstudy_pro\WWW\rabbitmq\worker\worker2.php

消費(fèi)者消費(fèi)消息ack確認(rèn)

用以確認(rèn)不會(huì)丟失消息

消費(fèi)消息
basic_consume($queue = ‘’, $consumer_tag = ‘’, $no_local = false, $no_ack = false, $exclusive = false, $nowait = false, $callback = null, $ticket = null, $arguments = array())
Getting started with message queue RabbitMQ and detailed explanation of PHP examples
no_ack=false,設(shè)置為手動(dòng)應(yīng)答
開啟后需要進(jìn)行消息的消費(fèi)確認(rèn)后才會(huì)進(jìn)行移除,否者該消息會(huì)一直存在消息隊(duì)列中
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

消費(fèi)端代碼
D:\phpstudy_pro\WWW\rabbitmq\worker\worker1.php

<?php require_once "../vendor/autoload.php";

use PhpAmqpLib\Connection\AMQPStreamConnection;


//建立connction
$connection = new AMQPStreamConnection(&#39;192.168.10.105&#39;, 5672, &#39;root&#39;, &#39;root&#39;, &#39;order&#39;);
//Channel
$channel = $connection->channel();

//聲明隊(duì)列名為:task_queue
$queue_name?=?'task_queue';
$channel->queue_declare($queue_name,?false,?true,?false,?false);

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

$callback?=?function?($msg)?{
????echo?'received?=?',?$msg->body?.?"\n";
????//確認(rèn)消息已被消費(fèi),從生產(chǎn)隊(duì)列中移除
????$msg->ack();
};

//設(shè)置消費(fèi)成功后才能繼續(xù)進(jìn)行下一個(gè)消費(fèi)
$channel->basic_qos(null,?1,?null);

//開啟消費(fèi)no_ack=false,設(shè)置為手動(dòng)應(yīng)答
$channel->basic_consume($queue_name,?'',?false,?false,?false,?false,?$callback);


//不斷的循環(huán)進(jìn)行消費(fèi)
while?($channel->is_open())?{
????$channel->wait();
}

//關(guān)閉連接
$channel->close();
$connection->close();

fanout模式生產(chǎn)者推送到交換器

發(fā)布/訂閱模式
是要是公用一個(gè)交換機(jī)的消費(fèi)端都能收到同樣的消息,類似廣播的功能

文檔:rabbitmq Publish/Subscribe
https://www.rabbitmq.com/tutorials/tutorial-three-php.html
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

rabbitmq Exchange類型

交換器、路由鍵、綁定

????Exchange:交換器。發(fā)送消息的AMQP實(shí)體。交換器拿到一個(gè)消息之后將它路由給一個(gè)或幾個(gè)隊(duì)列。它使用哪種路由算法是由交換機(jī)類型和被稱作綁定(Binding)的規(guī)則所決定的。RabbitMQ有四種類型。

????RoutingKey:路由鍵。生產(chǎn)者將消息發(fā)送給交換器。一般會(huì)指定一個(gè)RoutingKey,用來指定這個(gè)消息的路由規(guī)則,而這個(gè)RoutingKey需要與交換器類型和綁定鍵(BindingKey)聯(lián)合使用才能最終失效。

????Binding:綁定。綁定(Binding)是交換機(jī)(Exchange)將消息(Message)路由給隊(duì)列(Queue)所需遵循的規(guī)則。

#?四種模式
Direct??定向?消息與一個(gè)特定的路由鍵完全匹配

Topic??通配符?路由鍵和某模式進(jìn)行匹配

Fanout??廣播?發(fā)送到該類型交換機(jī)的消息都會(huì)被廣播到與該交換機(jī)綁定的所有隊(duì)列
Headers?不處理路由鍵,而是根據(jù)發(fā)送的消息內(nèi)容中的headers屬性進(jìn)行匹配

exchange_declare($exchange, $type, $passive = false, $durable = false, $auto_delete = true, $internal = false, $nowait = false, $arguments = array(), $ticket = null) 。試探性申請(qǐng)一個(gè)交換器,若該交換器不存在,則創(chuàng)建;若存在,則跳過。

Getting started with message queue RabbitMQ and detailed explanation of PHP examples
生產(chǎn)者代碼
D:\phpstudy_pro\WWW\rabbitmq\ps\pro.php

<?php require_once "../vendor/autoload.php";

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

//建立connction
$connection = new AMQPStreamConnection(&#39;192.168.10.105&#39;, 5672, &#39;root&#39;, &#39;root&#39;, &#39;order&#39;);
//Channel
$channel = $connection->channel();
//聲明交換器
$exc_name?=?'exch';
$channel->exchange_declare($exc_name,?'fanout',?false,?false,?false);

//聲明數(shù)據(jù)
$data?=?'this?is?fanout?message';
//創(chuàng)建消息
$msg?=?new?AMQPMessage($data,?['delivery_mode'?=>?AMQPMessage::DELIVERY_MODE_NON_PERSISTENT]);

//發(fā)布消息
$channel->basic_publish($msg,?$exc_name);
//關(guān)閉連接
$channel->close();
$connection->close();

Getting started with message queue RabbitMQ and detailed explanation of PHP examples

fanout模式消費(fèi)者消費(fèi)消息
是要是公用一個(gè)交換機(jī)的消費(fèi)端都能收到同樣的消息,類似廣播的功能

當(dāng)消費(fèi)端運(yùn)行時(shí)才會(huì)顯示該隊(duì)列
Getting started with message queue RabbitMQ and detailed explanation of PHP examples
消費(fèi)端:
D:\phpstudy_pro\WWW\rabbitmq\ps\worker1.php

<?php require_once "../vendor/autoload.php";

use PhpAmqpLib\Connection\AMQPStreamConnection;

//建立connction
$connection = new AMQPStreamConnection(&#39;192.168.10.105&#39;, 5672, &#39;root&#39;, &#39;root&#39;, &#39;order&#39;);
//Channel
$channel = $connection->channel();

//聲明交換器
$exc_name?=?'exch';
$channel->exchange_declare($exc_name,?'fanout',?false,?false,?false);

//獲取系統(tǒng)生成的消息隊(duì)列名稱
list($queue_name,?,)?=?$channel->queue_declare('',?false,?false,?true,?false);

//將隊(duì)列名與交換器名進(jìn)行綁定
$channel->queue_bind($queue_name,$exc_name);

$callback?=?function?($msg)?{
????echo?'received?=?',?$msg->body?.?"\n";
????//確認(rèn)消息已被消費(fèi),從生產(chǎn)隊(duì)列中移除
????$msg->ack();
};

//設(shè)置消費(fèi)成功后才能繼續(xù)進(jìn)行下一個(gè)消費(fèi)
$channel->basic_qos(null,?1,?null);

//開啟消費(fèi)no_ack=false,設(shè)置為手動(dòng)應(yīng)答
$channel->basic_consume($queue_name,?'',?false,?false,?false,?false,?$callback);

//不斷的循環(huán)進(jìn)行消費(fèi)
while?($channel->is_open())?{
????$channel->wait();
}

//關(guān)閉連接
$channel->close();
$connection->close();

direct模式消息隊(duì)列使用

文檔:
https://www.rabbitmq.com/tutorials/tutorial-four-php.html

用來指定不同的交換機(jī)和指定routing_key,在消費(fèi)端進(jìn)行消費(fèi)
Getting started with message queue RabbitMQ and detailed explanation of PHP examples
生產(chǎn)者代碼:
D:\phpstudy_pro\WWW\rabbitmq\routing\pro.php

<?php require_once "../vendor/autoload.php";

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

//建立connction
$connection = new AMQPStreamConnection(&#39;192.168.10.105&#39;, 5672, &#39;root&#39;, &#39;root&#39;, &#39;order&#39;);
//Channel
$channel = $connection->channel();
//聲明交換器
$exc_name?=?'direct_log';
//指定routing_key
$routing_key?=?'info';

//指定交換機(jī)類型為direct
$channel->exchange_declare($exc_name,?'direct',?false,?false,?false);

//聲明數(shù)據(jù)
$data?=?'this?is?'?.?$routing_key?.?'?message';
//創(chuàng)建消息
$msg?=?new?AMQPMessage($data,?['delivery_mode'?=>?AMQPMessage::DELIVERY_MODE_NON_PERSISTENT]);

//發(fā)布消息
//指定使用的routing_key
$channel->basic_publish($msg,?$exc_name,?$routing_key);
//關(guān)閉連接
$channel->close();
$connection->close();

消費(fèi)者代碼
D:\phpstudy_pro\WWW\rabbitmq\routing\info.php

<?php require_once "../vendor/autoload.php";

use PhpAmqpLib\Connection\AMQPStreamConnection;

//建立connction
$connection = new AMQPStreamConnection(&#39;192.168.10.105&#39;, 5672, &#39;root&#39;, &#39;root&#39;, &#39;order&#39;);
//Channel
$channel = $connection->channel();

//聲明交換器
$exc_name?=?'direct_log';
//指定routing_key
$routing_key?=?'info';

$channel->exchange_declare($exc_name,?'direct',?false,?false,?false);

//獲取系統(tǒng)生成的消息隊(duì)列名稱
list($queue_name,?,)?=?$channel->queue_declare('',?false,?false,?true,?false);

//將隊(duì)列名與交換器名進(jìn)行綁定,并指定routing_key
$channel->queue_bind($queue_name,$exc_name,$routing_key);

$callback?=?function?($msg)?{
????echo?'received?=?',?$msg->body?.?"\n";
????//確認(rèn)消息已被消費(fèi),從生產(chǎn)隊(duì)列中移除
????$msg->ack();
};

//設(shè)置消費(fèi)成功后才能繼續(xù)進(jìn)行下一個(gè)消費(fèi)
$channel->basic_qos(null,?1,?null);

//開啟消費(fèi)no_ack=false,設(shè)置為手動(dòng)應(yīng)答
$channel->basic_consume($queue_name,?'',?false,?false,?false,?false,?$callback);

//不斷的循環(huán)進(jìn)行消費(fèi)
while?($channel->is_open())?{
????$channel->wait();
}

//關(guān)閉連接
$channel->close();
$connection->close();

topic模式消息隊(duì)列使用

通配符的匹配模式

如消費(fèi)端中routing_key = ‘user.*’;
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

生產(chǎn)者:
指定routing_key= ‘user.top’

<?php require_once "../vendor/autoload.php";

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

//建立connction
$connection = new AMQPStreamConnection(&#39;192.168.10.105&#39;, 5672, &#39;root&#39;, &#39;root&#39;, &#39;order&#39;);
//Channel
$channel = $connection->channel();
//聲明交換器
$exc_name?=?'topic_log';
//指定routing_key
$routing_key?=?'user.top';

//指定交換機(jī)類型為direct
$channel->exchange_declare($exc_name,?'topic',?false,?false,?false);

//聲明數(shù)據(jù)
$data?=?'this?is?'?.?$routing_key?.?'?message';
//創(chuàng)建消息
$msg?=?new?AMQPMessage($data,?['delivery_mode'?=>?AMQPMessage::DELIVERY_MODE_NON_PERSISTENT]);

//發(fā)布消息
//指定使用的routing_key
$channel->basic_publish($msg,?$exc_name,?$routing_key);
//關(guān)閉連接
$channel->close();
$connection->close();

消費(fèi)者
消費(fèi)端中routing_key = ‘user.*’;

<?php require_once "../vendor/autoload.php";

use PhpAmqpLib\Connection\AMQPStreamConnection;

//建立connction
$connection = new AMQPStreamConnection(&#39;192.168.10.105&#39;, 5672, &#39;root&#39;, &#39;root&#39;, &#39;order&#39;);
//Channel
$channel = $connection->channel();

//聲明交換器
$exc_name?=?'direct_log';
//指定routing_key
$routing_key?=?'user.*';

$channel->exchange_declare($exc_name,?'topic',?false,?false,?false);

//獲取系統(tǒng)生成的消息隊(duì)列名稱
list($queue_name,?,)?=?$channel->queue_declare('',?false,?false,?true,?false);

//將隊(duì)列名與交換器名進(jìn)行綁定,并指定routing_key
$channel->queue_bind($queue_name,$exc_name,$routing_key);

$callback?=?function?($msg)?{
????echo?'received?=?',?$msg->body?.?"\n";
????//確認(rèn)消息已被消費(fèi),從生產(chǎn)隊(duì)列中移除
????$msg->ack();
};

//設(shè)置消費(fèi)成功后才能繼續(xù)進(jìn)行下一個(gè)消費(fèi)
$channel->basic_qos(null,?1,?null);

//開啟消費(fèi)no_ack=false,設(shè)置為手動(dòng)應(yīng)答
$channel->basic_consume($queue_name,?'',?false,?false,?false,?false,?$callback);

//不斷的循環(huán)進(jìn)行消費(fèi)
while?($channel->is_open())?{
????$channel->wait();
}

//關(guān)閉連接
$channel->close();
$connection->close();

推薦學(xué)習(xí):《PHP視頻教程

The above is the detailed content of Getting started with message queue RabbitMQ and detailed explanation of PHP examples. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why We Comment: A PHP Guide Why We Comment: A PHP Guide Jul 15, 2025 am 02:48 AM

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

How to Install PHP on Windows How to Install PHP on Windows Jul 15, 2025 am 02:46 AM

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

PHP Syntax: The Basics PHP Syntax: The Basics Jul 15, 2025 am 02:46 AM

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

PHP 8 Installation Guide PHP 8 Installation Guide Jul 16, 2025 am 03:41 AM

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

What is PHP and What is it Used For? What is PHP and What is it Used For? Jul 16, 2025 am 03:45 AM

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

python if else example python if else example Jul 15, 2025 am 02:55 AM

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

Your First PHP Script: A Practical Introduction Your First PHP Script: A Practical Introduction Jul 16, 2025 am 03:42 AM

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

how to handle undefined index in PHP how to handle undefined index in PHP Jul 15, 2025 am 02:08 AM

The "undefinedindex" error occurs because a key that does not exist in the array is accessed. Solutions include: 1. Use isset() to check whether the key exists, which is suitable for processing user input; 2. Use array_key_exists() to determine whether the key is set, and it can be recognized even if the value is null; 3. Use the empty merge operator?? to set the default value to avoid directly accessing undefined keys; in addition, you need to pay attention to common problems such as the spelling of form field names, the database result is empty, the array unpacking is not verified, the child keys are not checked in foreach, and the session_start() is not called.

See all articles