찾다
백엔드 개발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는 지난 수십 년 동안 네트워크를 형성했으며 웹 개발에서 계속 중요한 역할을 할 것입니다. 1) PHP는 1994 년에 시작되었으며 MySQL과의 원활한 통합으로 인해 개발자에게 최초의 선택이되었습니다. 2) 핵심 기능에는 동적 컨텐츠 생성 및 데이터베이스와의 통합이 포함되며 웹 사이트를 실시간으로 업데이트하고 맞춤형 방식으로 표시 할 수 있습니다. 3) PHP의 광범위한 응용 및 생태계는 장기적인 영향을 미쳤지 만 버전 업데이트 및 보안 문제에 직면 해 있습니다. 4) PHP7의 출시와 같은 최근 몇 년간의 성능 향상을 통해 현대 언어와 경쟁 할 수 있습니다. 5) 앞으로 PHP는 컨테이너화 및 마이크로 서비스와 같은 새로운 도전을 다루어야하지만 유연성과 활발한 커뮤니티로 인해 적응력이 있습니다.

PHP를 사용하는 이유는 무엇입니까? 설명 된 장점과 혜택PHP를 사용하는 이유는 무엇입니까? 설명 된 장점과 혜택Apr 16, 2025 am 12:16 AM

PHP의 핵심 이점에는 학습 용이성, 강력한 웹 개발 지원, 풍부한 라이브러리 및 프레임 워크, 고성능 및 확장 성, 크로스 플랫폼 호환성 및 비용 효율성이 포함됩니다. 1) 배우고 사용하기 쉽고 초보자에게 적합합니다. 2) 웹 서버와 우수한 통합 및 여러 데이터베이스를 지원합니다. 3) Laravel과 같은 강력한 프레임 워크가 있습니다. 4) 최적화를 통해 고성능을 달성 할 수 있습니다. 5) 여러 운영 체제 지원; 6) 개발 비용을 줄이기위한 오픈 소스.

신화를 폭로 : PHP가 실제로 죽은 언어입니까?신화를 폭로 : PHP가 실제로 죽은 언어입니까?Apr 16, 2025 am 12:15 AM

PHP는 죽지 않았습니다. 1) PHP 커뮤니티는 성능 및 보안 문제를 적극적으로 해결하고 PHP7.x는 성능을 향상시킵니다. 2) PHP는 최신 웹 개발에 적합하며 대규모 웹 사이트에서 널리 사용됩니다. 3) PHP는 배우기 쉽고 서버가 잘 수행되지만 유형 시스템은 정적 언어만큼 엄격하지 않습니다. 4) PHP는 컨텐츠 관리 및 전자 상거래 분야에서 여전히 중요하며 생태계는 계속 발전하고 있습니다. 5) Opcache 및 APC를 통해 성능을 최적화하고 OOP 및 설계 패턴을 사용하여 코드 품질을 향상시킵니다.

PHP vs. Python 토론 : 어느 것이 더 낫습니까?PHP vs. Python 토론 : 어느 것이 더 낫습니까?Apr 16, 2025 am 12:03 AM

PHP와 Python에는 고유 한 장점과 단점이 있으며 선택은 프로젝트 요구 사항에 따라 다릅니다. 1) PHP는 웹 개발, 배우기 쉽고 풍부한 커뮤니티 리소스에 적합하지만 구문은 현대적이지 않으며 성능과 보안에주의를 기울여야합니다. 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) 준비 방법을 통해 전처리 명세서를 작성하고 자리 표시자를 사용하여 데이터를 전달하고 방법을 실행하십시오. 3) 쿼리 결과를 처리하고 코드의 보안 및 성능을 보장합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.