目录
Routing(路由)
(using php-amqplib)
Bindings(捆绑)
Direct exchange(定向交换器)
Multiple bindings(多重捆绑)
Emitting logs(日志发布)
Subscribing(订阅)
Putting it all together(合体!!!还来??哈哈)
首页 后端开发 php教程 译-PHP rabbitMQ Tutorial-4

译-PHP rabbitMQ Tutorial-4

Jun 23, 2016 pm 01:59 PM

Routing(路由)

(using php-amqplib)


In the previous tutorial we built a simple logging system. We were able to broadcast log messages to many receivers.

上次,我们构建了一个简单的日志系统来广播消息到多个接收者。

In this tutorial we're going to add a feature to it - we're going to make it possible to subscribe only to a subset of the messages. For example, we will be able to direct only critical error messages to the log file (to save disk space), while still being able to print all of the log messages on the console.

这次我们要添加一个特性上去??使它可以仅仅收听部分消息。例如,我们可以仅指示存储致命错误消息到日志文件(存储到硬盘),然而仍然可以在控制台打印所有消息。

Bindings(捆绑)

In previous examples we were already creating bindings. You may recall code like:

上个例子,我们已经创建了捆绑。你可能想起来了,如下:

$channel->queue_bind($queue_name, 'logs');
登录后复制

A binding is a relationship between an exchange and a queue. This can be simply read as: the queue is interested in messages from this exchange.

交换器和队列之间的关系称之为捆绑。可以简单理解为:这个队列对这个特定的交换器的消息感兴趣。

Bindings can take an extra routing_key parameter. To avoid the confusion with a $channel::basic_publish parameter we're going to call it a binding key. This is how we could create a binding with a key:

捆绑可以设置一个额外的routing_key参数。为了避免和$channel:basic_publish的参数混淆,我们就叫它捆绑键(banding key)。这就是我们如何用key来创建一个捆绑。

$binding_key = 'black';$channel->queue_bind($queue_name, $exchange_name, $binding_key);
登录后复制

The meaning of a binding key depends on the exchange type. The fanout exchanges, which we used previously, simply ignored its value.

binding key的意义在于交换器类型。之前用的fanout类型的交换器会简单忽略这个值。

Direct exchange(定向交换器)

Our logging system from the previous tutorial broadcasts all messages to all consumers. We want to extend that to allow filtering messages based on their severity. For example we may want the script which is writing log messages to the disk to only receive critical errors, and not waste disk space on warning or info log messages.

之前的日志系统广播所有消息到所有的消费者。我们想扩展它??允许基于严重程度来过滤消息。例如,我们可能想让日志持久化的脚本仅仅持久化致命错误,就不会在警告和信息(info)消息上浪费硬盘空间。

We were using a fanout exchange, which doesn't give us much flexibility - it's only capable of mindless broadcasting.

我们用的fanout交换器没给我们带来多少灵活性??它仅仅是无头蒙的广播。

We will use a direct exchange instead. The routing algorithm behind a direct exchange is simple - a message goes to the queues whose binding key exactly matches the routing key of the message.

我们将用定向交换器来代替fanout交换器。定向交换器背后的算法很简单??消息会推送到:消息routing key和队列binding key完全匹配的的队列中。

To illustrate that, consider the following setup:

为了阐述清楚,思考一下下面的结构:

In this setup, we can see the direct exchange X with two queues bound to it. The first queue is bound with binding key orange, and the second has two bindings, one with binding key blackand the other one with green.

在这个结构上,我们可以看到交换器X上捆绑了两个队列。第一个队列用binding key 橘子 捆绑,第二个有两个绑定,

头一个用的是binding key 黑色,另外一个是用的是绿色.

In such a setup a message published to the exchange with a routing key orange will be routed to queue Q1. Messages with a routing key of black or green will go to Q2. All other messages will be discarded.

这个结构中,派送到交换器的带有routing key 橘子的消息会被路由到队列Q1. 带有黑色和绿色routing key的消息会进入到Q2. 所有这之外消息都会被丢弃。

Multiple bindings(多重捆绑)

It is perfectly legal to bind multiple queues with the same binding key. In our example we could add a binding between X and Q1 with binding key black. In that case, the direct exchange will behave like fanout and will broadcast the message to all the matching queues. A message with routing key black will be delivered to both Q1 and Q2.

用相同的binding key捆绑多个队列毛问题没有。我们的例子中,我们可以用黑色来建立X和Q1之间的捆绑。这种情况下,定向交换器的行为就回像fanout交换器一样,广播消息到所有匹配的队列。Q1和Q2都会收到带有routing key黑色的消息。

Emitting logs(日志发布)

We'll use this model for our logging system. Instead of fanout we'll send messages to a direct exchange. We will supply the log severity as a routing key. That way the receiving script will be able to select the severity it wants to receive. Let's focus on emitting logs first.

我们将应用这种模式到我们的日志系统。与fanout交换器不同的是我们发送消息到指定的交换器。用日志严重等级来作为

routing key。 那样的话接收脚本就可以根据严重等级来选择想要接收的消息。我们先来把发布日志搞定。

As always, we need to create an exchange first:

老样子,先要创建一个交换器:

$channel->exchange_declare('direct_logs', 'direct', false, false, false);
登录后复制

And we're ready to send a message:

准备发射!!!??消息 - -#

$channel->exchange_declare('direct_logs', 'direct', false, false, false);$channel->basic_publish($msg, 'direct_logs', $severity);
登录后复制

To simplify things we will assume that 'severity' can be one of 'info', 'warning', 'error'.

简单起见,我们假定严重等级可以是info,warning,error中的一个。

Subscribing(订阅)

Receiving messages will work just like in the previous tutorial, with one exception - we're going to create a new binding for each severity we're interested in.

接收消息就跟之前一样,但有一点不同??我们得为每一个感兴趣的严重等级创建一个捆绑。

foreach($severities as $severity) {    $channel->queue_bind($queue_name, 'direct_logs', $severity);}
登录后复制

Putting it all together(合体!!!还来??哈哈)

The code for emit_log_direct.php class:

emit_log_direct.php类代码:

channel();$channel->exchange_declare('direct_logs', 'direct', false, false, false);$severity = $argv[1];if(empty($severity)) $severity = "info";$data = implode(' ', array_slice($argv, 2));if(empty($data)) $data = "Hello World!";$msg = new AMQPMessage($data);$channel->basic_publish($msg, 'direct_logs', $severity);echo " [x] Sent ",$severity,':',$data," \n";$channel->close();$connection->close();?>
登录后复制

The code for receive_logs_direct.php:

receive_logs_direct.php代码:

channel();$channel->exchange_declare('direct_logs', 'direct', false, false, false);list($queue_name, ,) = $channel->queue_declare("", false, false, true, false);$severities = array_slice($argv, 1);if(empty($severities )) {    file_put_contents('php://stderr', "Usage: $argv[0] [info] [warning] [error]\n");    exit(1);}foreach($severities as $severity) {    $channel->queue_bind($queue_name, 'direct_logs', $severity);}echo ' [*] Waiting for logs. To exit press CTRL+C', "\n";$callback = function($msg){  echo ' [x] ',$msg->delivery_info['routing_key'], ':', $msg->body, "\n";};$channel->basic_consume($queue_name, '', false, true, false, false, $callback);while(count($channel->callbacks)) {    $channel->wait();}$channel->close();$connection->close();?>
登录后复制

If you want to save only 'warning' and 'error' (and not 'info') log messages to a file, just open a console and type:

如果你想仅存储warning和error的消息到日志文件,就打开控制台输入:

$ php receive_logs_direct.php warning error > logs_from_rabbit.log
登录后复制

If you'd like to see all the log messages on your screen, open a new terminal and do:

要想在屏幕上查看所有的消息,打开一个新窗口输入:

$ php receive_logs_direct.php info warning error [*] Waiting for logs. To exit press CTRL+C
登录后复制

And, for example, to emit an error log message just type:

对了,例如,要发布错误消息就输入:

$ php emit_log_direct.php error "Run. Run. Or it will explode." [x] Sent 'error':'Run. Run. Or it will explode.'
登录后复制

(Full source code for (emit_log_direct.php source) and (receive_logs_direct.php source))

emit_log_direct.php和receive_logs_direct.php的源码

Move on to tutorial 5 to find out how to listen for messages based on a pattern.

下回呢我们讲讲如何基于模式来收听消息。

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

在PHP API中说明JSON Web令牌(JWT)及其用例。 在PHP API中说明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一种基于JSON的开放标准,用于在各方之间安全地传输信息,主要用于身份验证和信息交换。1.JWT由Header、Payload和Signature三部分组成。2.JWT的工作原理包括生成JWT、验证JWT和解析Payload三个步骤。3.在PHP中使用JWT进行身份验证时,可以生成和验证JWT,并在高级用法中包含用户角色和权限信息。4.常见错误包括签名验证失败、令牌过期和Payload过大,调试技巧包括使用调试工具和日志记录。5.性能优化和最佳实践包括使用合适的签名算法、合理设置有效期、

会话如何劫持工作,如何在PHP中减轻它? 会话如何劫持工作,如何在PHP中减轻它? Apr 06, 2025 am 12:02 AM

会话劫持可以通过以下步骤实现:1.获取会话ID,2.使用会话ID,3.保持会话活跃。在PHP中防范会话劫持的方法包括:1.使用session_regenerate_id()函数重新生成会话ID,2.通过数据库存储会话数据,3.确保所有会话数据通过HTTPS传输。

描述扎实的原则及其如何应用于PHP的开发。 描述扎实的原则及其如何应用于PHP的开发。 Apr 03, 2025 am 12:04 AM

SOLID原则在PHP开发中的应用包括:1.单一职责原则(SRP):每个类只负责一个功能。2.开闭原则(OCP):通过扩展而非修改实现变化。3.里氏替换原则(LSP):子类可替换基类而不影响程序正确性。4.接口隔离原则(ISP):使用细粒度接口避免依赖不使用的方法。5.依赖倒置原则(DIP):高低层次模块都依赖于抽象,通过依赖注入实现。

在PHPStorm中如何进行CLI模式的调试? 在PHPStorm中如何进行CLI模式的调试? Apr 01, 2025 pm 02:57 PM

在PHPStorm中如何进行CLI模式的调试?在使用PHPStorm进行开发时,有时我们需要在命令行界面(CLI)模式下调试PHP�...

如何在系统重启后自动设置unixsocket的权限? 如何在系统重启后自动设置unixsocket的权限? Mar 31, 2025 pm 11:54 PM

如何在系统重启后自动设置unixsocket的权限每次系统重启后,我们都需要执行以下命令来修改unixsocket的权限:sudo...

解释PHP中的晚期静态绑定(静态::)。 解释PHP中的晚期静态绑定(静态::)。 Apr 03, 2025 am 12:04 AM

静态绑定(static::)在PHP中实现晚期静态绑定(LSB),允许在静态上下文中引用调用类而非定义类。1)解析过程在运行时进行,2)在继承关系中向上查找调用类,3)可能带来性能开销。

如何用PHP的cURL库发送包含JSON数据的POST请求? 如何用PHP的cURL库发送包含JSON数据的POST请求? Apr 01, 2025 pm 03:12 PM

使用PHP的cURL库发送JSON数据在PHP开发中,经常需要与外部API进行交互,其中一种常见的方式是使用cURL库发送POST�...

See all articles