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

Table of Contents
Introduction to message queue and message queue application scenarios
RabbitMQ
rabbitmq installation startup
simple模式消費者接受消息
worker模式生產(chǎn)消費消息
fanout模式生產(chǎn)者推送到交換器
direct模式消息隊列使用
topic模式消息隊列使用
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包,手動下載后上傳至服務器,我在使用wget下載后無法安裝,這里沒明白


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

#?驗證安裝是否成功
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包,手動下載后上傳至服務器,我在使用wget下載后無法安裝,這里沒明白


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

#?啟動
systemctl?start?rabbitmq-server

#?關閉
systemctl?stop?rabbitmq-server

#?查看默認端口服務是否啟動
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)

#?啟動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

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

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

#?查看當前用戶列表????
rabbitmqctl?list_users

#?設置用戶角色的命令為:?
rabbitmqctl?set_user_tags?User?Tag??
rabbitmqctl?set_user_tags?root?administrator
#?User為用戶名,?Tag為角色名(對應于上面的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?".*"?".*"?".*"
?".*"?".*"?".*"后邊三個.*分別代表:配置權限、寫權限、讀權限

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

#?升級composer
composer?self-update

#php.ini?打開?sockets?擴展

#下載指定版本
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都建立一個Connection,在消息量大的時候建立TCP Connection的開銷將是巨大的,效率也較低。Channel是在connection內(nèi)部建立的邏輯連接Channel作為輕量級的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();
//聲明隊列名為: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);
//關閉連接
$channel->close();
$connection->close();

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

simple模式消費者接受消息

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();

//聲明隊列名為: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";
};
//開啟消費
$channel->basic_consume($queue_name,?'',?false,?true,?false,?false,?$callback);

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

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

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

rabbitmq Work Queues
一個生產(chǎn)者對應多個消費者,消費特別慢時增加幾個消費分發(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都建立一個Connection,在消息量大的時候建立TCP Connection的開銷將是巨大的,效率也較低。Channel是在connection內(nèi)部建立的邏輯連接Channel作為輕量級的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();
//聲明隊列名為: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);
}

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

消費者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();

//聲明隊列名為: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";
};
//開啟消費
$channel->basic_consume($queue_name,?'',?false,?true,?false,?false,?$callback);

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

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

消費者worker2,代碼和worker1一樣,同時運行開啟后會一起消費
D:\phpstudy_pro\WWW\rabbitmq\worker\worker2.php

消費者消費消息ack確認

用以確認不會丟失消息

消費消息
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,設置為手動應答
開啟后需要進行消息的消費確認后才會進行移除,否者該消息會一直存在消息隊列中
Getting started with message queue RabbitMQ and detailed explanation of PHP examples

消費端代碼
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();

//聲明隊列名為: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";
????//確認消息已被消費,從生產(chǎn)隊列中移除
????$msg->ack();
};

//設置消費成功后才能繼續(xù)進行下一個消費
$channel->basic_qos(null,?1,?null);

//開啟消費no_ack=false,設置為手動應答
$channel->basic_consume($queue_name,?'',?false,?false,?false,?false,?$callback);


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

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

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

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

文檔: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實體。交換器拿到一個消息之后將它路由給一個或幾個隊列。它使用哪種路由算法是由交換機類型和被稱作綁定(Binding)的規(guī)則所決定的。RabbitMQ有四種類型。

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

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

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

Topic??通配符?路由鍵和某模式進行匹配

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

exchange_declare($exchange, $type, $passive = false, $durable = false, $auto_delete = true, $internal = false, $nowait = false, $arguments = array(), $ticket = null) 。試探性申請一個交換器,若該交換器不存在,則創(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);
//關閉連接
$channel->close();
$connection->close();

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

fanout模式消費者消費消息
是要是公用一個交換機的消費端都能收到同樣的消息,類似廣播的功能

當消費端運行時才會顯示該隊列
Getting started with message queue RabbitMQ and detailed explanation of PHP examples
消費端:
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)生成的消息隊列名稱
list($queue_name,?,)?=?$channel->queue_declare('',?false,?false,?true,?false);

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

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

//設置消費成功后才能繼續(xù)進行下一個消費
$channel->basic_qos(null,?1,?null);

//開啟消費no_ack=false,設置為手動應答
$channel->basic_consume($queue_name,?'',?false,?false,?false,?false,?$callback);

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

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

direct模式消息隊列使用

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

用來指定不同的交換機和指定routing_key,在消費端進行消費
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';

//指定交換機類型為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);
//關閉連接
$channel->close();
$connection->close();

消費者代碼
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)生成的消息隊列名稱
list($queue_name,?,)?=?$channel->queue_declare('',?false,?false,?true,?false);

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

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

//設置消費成功后才能繼續(xù)進行下一個消費
$channel->basic_qos(null,?1,?null);

//開啟消費no_ack=false,設置為手動應答
$channel->basic_consume($queue_name,?'',?false,?false,?false,?false,?$callback);

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

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

topic模式消息隊列使用

通配符的匹配模式

如消費端中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';

//指定交換機類型為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);
//關閉連接
$channel->close();
$connection->close();

消費者
消費端中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)生成的消息隊列名稱
list($queue_name,?,)?=?$channel->queue_declare('',?false,?false,?true,?false);

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

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

//設置消費成功后才能繼續(xù)進行下一個消費
$channel->basic_qos(null,?1,?null);

//開啟消費no_ack=false,設置為手動應答
$channel->basic_consume($queue_name,?'',?false,?false,?false,?false,?$callback);

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

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

推薦學習:《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)

Hot Topics

PHP Tutorial
1502
276
PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution Jul 25, 2025 pm 07:06 PM

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.

See all articles