搜索
首页后端开发php教程译-PHP rabbitMQ Tutorial-4

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
PHP:服务器端脚本语言的简介PHP:服务器端脚本语言的简介Apr 16, 2025 am 12:18 AM

PHP是一种服务器端脚本语言,用于动态网页开发和服务器端应用程序。1.PHP是一种解释型语言,无需编译,适合快速开发。2.PHP代码嵌入HTML中,易于网页开发。3.PHP处理服务器端逻辑,生成HTML输出,支持用户交互和数据处理。4.PHP可与数据库交互,处理表单提交,执行服务器端任务。

PHP和网络:探索其长期影响PHP和网络:探索其长期影响Apr 16, 2025 am 12:17 AM

PHP在过去几十年中塑造了网络,并将继续在Web开发中扮演重要角色。1)PHP起源于1994年,因其易用性和与MySQL的无缝集成成为开发者首选。2)其核心功能包括生成动态内容和与数据库的集成,使得网站能够实时更新和个性化展示。3)PHP的广泛应用和生态系统推动了其长期影响,但也面临版本更新和安全性挑战。4)近年来的性能改进,如PHP7的发布,使其能与现代语言竞争。5)未来,PHP需应对容器化、微服务等新挑战,但其灵活性和活跃社区使其具备适应能力。

为什么要使用PHP?解释的优点和好处为什么要使用PHP?解释的优点和好处Apr 16, 2025 am 12:16 AM

PHP的核心优势包括易于学习、强大的web开发支持、丰富的库和框架、高性能和可扩展性、跨平台兼容性以及成本效益高。1)易于学习和使用,适合初学者;2)与web服务器集成好,支持多种数据库;3)拥有如Laravel等强大框架;4)通过优化可实现高性能;5)支持多种操作系统;6)开源,降低开发成本。

揭穿神话:PHP真的是一种死语吗?揭穿神话:PHP真的是一种死语吗?Apr 16, 2025 am 12:15 AM

PHP没有死。1)PHP社区积极解决性能和安全问题,PHP7.x提升了性能。2)PHP适合现代Web开发,广泛用于大型网站。3)PHP易学且服务器表现出色,但类型系统不如静态语言严格。4)PHP在内容管理和电商领域仍重要,生态系统不断进化。5)通过OPcache和APC等优化性能,使用OOP和设计模式提升代码质量。

PHP与Python辩论:哪个更好?PHP与Python辩论:哪个更好?Apr 16, 2025 am 12:03 AM

PHP和Python各有优劣,选择取决于项目需求。1)PHP适合Web开发,易学,社区资源丰富,但语法不够现代,性能和安全性需注意。2)Python适用于数据科学和机器学习,语法简洁,易学,但执行速度和内存管理有瓶颈。

PHP的目的:构建动态网站PHP的目的:构建动态网站Apr 15, 2025 am 12:18 AM

PHP用于构建动态网站,其核心功能包括:1.生成动态内容,通过与数据库对接实时生成网页;2.处理用户交互和表单提交,验证输入并响应操作;3.管理会话和用户认证,提供个性化体验;4.优化性能和遵循最佳实践,提升网站效率和安全性。

PHP:处理数据库和服务器端逻辑PHP:处理数据库和服务器端逻辑Apr 15, 2025 am 12:15 AM

PHP在数据库操作和服务器端逻辑处理中使用MySQLi和PDO扩展进行数据库交互,并通过会话管理等功能处理服务器端逻辑。1)使用MySQLi或PDO连接数据库,执行SQL查询。2)通过会话管理等功能处理HTTP请求和用户状态。3)使用事务确保数据库操作的原子性。4)防止SQL注入,使用异常处理和关闭连接来调试。5)通过索引和缓存优化性能,编写可读性高的代码并进行错误处理。

您如何防止PHP中的SQL注入? (准备的陈述,PDO)您如何防止PHP中的SQL注入? (准备的陈述,PDO)Apr 15, 2025 am 12:15 AM

在PHP中使用预处理语句和PDO可以有效防范SQL注入攻击。1)使用PDO连接数据库并设置错误模式。2)通过prepare方法创建预处理语句,使用占位符和execute方法传递数据。3)处理查询结果并确保代码的安全性和性能。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
4 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
4 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
1 个月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它们
1 个月前By尊渡假赌尊渡假赌尊渡假赌

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

禅工作室 13.0.1

禅工作室 13.0.1

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

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。