译-PHP rabbitMQ Tutorial-5
Topics (usingphp-amqplib) In theprevious tutorialwe improved our logging system. Instead of using afanoutexchange only capable of dummy broadcasting, we used adirect one, and gained a possibility of selectively receiving the logs. 上一节,
Topics
(using php-amqplib)
In the previous tutorial we improved our logging system. Instead of using a fanout exchange only capable of dummy broadcasting, we used a direct one, and gained a possibility of selectively receiving the logs.
上一节,我们改进了日志系统。取代了fanout交换器仅仅会傻乎乎的广播,我们使用了定向交换器,使得选择性接收消息成为可能。
Although using the direct exchange improved our system, it still has limitations - it can't do routing based on multiple criteria.
尽管使用定向交换器改善了我们的系统,但它仍有局限性——不能基于多重条件进行路由。
In our logging system we might want to subscribe to not only logs based on severity, but also based on the source which emitted the log. You might know this concept from the syslog unix tool, which routes logs based on both severity (info/warn/crit...) and facility (auth/cron/kern...).
在日志系统中,我们可能想不仅订阅基于严重等级的内容,而且订阅基于消息发布来源的内容。你可以从syslog unix工具中得知这个概念——基于严重性和设备路由日志。
That would give us a lot of flexibility - we may want to listen to just critical errors coming from 'cron' but also all logs from 'kern'.
那会给我们带来很大的灵活性——我们可能想只是收听来自cron的致命错误和来自kern的所有消息。
To implement that in our logging system we need to learn about a more complex topic exchange.
为了在我们的日志系统上实现这种灵活性,我们需要学习一下更为复杂一些的topic交换器。
Topic exchange
Messages sent to a topic exchange can't have an arbitrary routing_key - it must be a list of words, delimited by dots. The words can be anything, but usually they specify some features connected to the message. A few valid routing key examples: "stock.usd.nyse", "nyse.vmw", "quick.orange.rabbit". There can be as many words in the routing key as you like, up to the limit of 255 bytes.
发送到topic交换器的消息不能给一个任意的routing_key——它必须是一个由逗号分隔的单词列表。
The binding key must also be in the same form. The logic behind the topic exchange is similar to a direct one - a message sent with a particular routing key will be delivered to all the queues that are bound with a matching binding key. However there are two important special cases for binding keys:
binding key也必须是同样的格式。topic交换器背后的逻辑和定向交换器类似——带有特定routing key的消息会被派送到所有捆绑了与routing key相匹配的binding key的队列。
- * (star) can substitute for exactly one word.
- *(星号)可以代表一个单词
- # (hash) can substitute for zero or more words.
- #(井号)可以代表零个或多个单词
It's easiest to explain this in an example:
In this example, we're going to send messages which all describe animals. The messages will be sent with a routing key that consists of three words (two dots). The first word in the routing key will describe speed, second a colour and third a species: "
这个例子中,我们将发送所有描述动物的消息。发送时,这些消息带有由三个单词(两个点号分隔)组成的routing key.其中起一个单词用来表述速度,第二个用来表示颜色,最后一个用来表示种类:"
We created three bindings: Q1 is bound with binding key "*.orange.*" and Q2 with "*.*.rabbit" and "lazy.#".
创建三个捆绑:用 "*.orange.*" 来绑定Q1,用 "*.*.rabbit" 和"lazy.#"来绑定Q2.
These bindings can be summarised as:
这几个捆绑可以概括为:
- Q1 is interested in all the orange animals.
- Q1喜欢所有橙色的动物
- Q2 wants to hear everything about rabbits, and everything about lazy animals.
- Q2想知道所有关于兔子和懒惰动物的事情
A message with a routing key set to "quick.orange.rabbit" will be delivered to both queues. Message "lazy.orange.elephant" also will go to both of them. On the other hand "quick.orange.fox" will only go to the first queue, and "lazy.brown.fox" only to the second. "lazy.pink.rabbit" will be delivered to the second queue only once, even though it matches two bindings. "quick.brown.fox" doesn't match any binding so it will be discarded.
这两个队列都会接收到routing key设置成"quick.orange.rabbit"的消息。设置成"lazy.orange.elephant"的也一样。
但"quick.orange.fox"仅仅会进入第一个队列,而"lazy.brown.fox"则仅会进入第二个队列。"lazy.pink.rabbit"仅仅会进入到第二个队列一次,虽然它可以匹配到两个困难规则。由于"quick.brown.fox"和谁都匹配不上,所以会被丢弃。
What happens if we break our contract and send a message with one or four words, like "orange" or "quick.orange.male.rabbit"? Well, these messages won't match any bindings and will be lost.
要是打破了我们的约束会怎样?比如,发送带有一个或是四个单词的,像"orange"或"quick.orange.male.rabbit"的消息。
好吧!消息会丢失,因为它不匹配任何捆绑规则。
On the other hand "lazy.orange.male.rabbit", even though it has four words, will match the last binding and will be delivered to the second queue.
但是 "lazy.orange.male.rabbit"这种routing key,尽管它有四个单词,但是还是会进入到第二个队列(为喵呢?你来说说)
Topic exchange
Topic exchange is powerful and can behave like other exchanges.
Topic 交换器很强大,它可以模拟其他交换器的行为
When a queue is bound with "#" (hash) binding key - it will receive all the messages, regardless of the routing key - like in fanout exchange.
当一个队列捆绑一个#的binding key——它会像fanout交换器一样,忽略掉routing key,接收所有的消息.(还记得#代表什喵么?)
When special characters "*" (star) and "#" (hash) aren't used in bindings, the topic exchange will behave just like a direct one.
在捆绑中如果没有使用特殊字符星号和井号,topic交换器的行为就跟定向交换器一样。
Putting it all together(合体!!!烦死了是吧?哈,还有一次!)
We're going to use a topic exchange in our logging system. We'll start off with a working assumption that the routing keys of logs will have two words: "
在我们的日志系统中使用topic交换器。我们假设日志的routing keyes有"
The code is almost the same as in the previous tutorial.
代码和之前的几乎一妈生的。
The code for emit_log_topic.php:
emit_log_topic.php代码:
<?php require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLib\Connection\AMQPConnection; use PhpAmqpLib\Message\AMQPMessage; $connection = new AMQPConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->exchange_declare('topic_logs', 'topic', false, false, false); $routing_key = $argv[1]; if(empty($routing_key)) $routing_key = "anonymous.info"; $data = implode(' ', array_slice($argv, 2)); if(empty($data)) $data = "Hello World!"; $msg = new AMQPMessage($data); $channel->basic_publish($msg, 'topic_logs', $routing_key); echo " [x] Sent ",$routing_key,':',$data," \n"; $channel->close(); $connection->close(); ?>
The code for receive_logs_topic.php:
<?php require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLib\Connection\AMQPConnection; $connection = new AMQPConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->exchange_declare('topic_logs', 'topic', false, false, false); list($queue_name, ,) = $channel->queue_declare("", false, false, true, false); $binding_keys = array_slice($argv, 1); if( empty($binding_keys )) { file_put_contents('php://stderr', "Usage: $argv[0] [binding_key]\n"); exit(1); } foreach($binding_keys as $binding_key) { $channel->queue_bind($queue_name, 'topic_logs', $binding_key); } 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(); ?>
To receive all the logs:
接收所有日志:
$ php receive_logs_topic.php "#"
To receive all logs from the facility "kern":
接收所有来自kern的日志:
$ phpreceive_logs_topic.php "kern.*"
Or if you want to hear only about "critical" logs:
或是你想仅仅接收”致命“日志
$ php receive_logs_topic.php "*.critical"
You can create multiple bindings:
你也可以多重绑定
$ php receive_logs_topic.php "kern.*" "*.critical"
And to emit a log with a routing key "kern.critical" type:
发布一个带有"kern.critical"routing key的日志就输入:
$ php emit_log_topic.php "kern.critical" "A critical kernel error"
Have fun playing with these programs. Note that the code doesn't make any assumption about the routing or binding keys, you may want to play with more than two routing key parameters.
玩的开心哈!注意上面的代码没有做路由或捆绑的例子,有可能想体验两个以上的routing key参数。
Some teasers:
- Will "*" binding catch a message sent with an empty routing key?
- 星号会匹配带有空routing key的消息吗?
- Will "#.*" catch a message with a string ".." as a key? Will it catch a message with a single word key?
- "#.*"会匹配".."的消息吗? 它是匹配到一个单一的单词吗?
- How different is "a.*.#" from "a.#"?
- "a.*.#"和"a.#"有啥不同?
(Full source code for emit_log_topic.php and receive_logs_topic.php)
emit_log_topic.php和receive_logs_topic.php源码。
Next, find out how to do a round trip message as a remote procedure call in tutorial 6
下次,我们讲如何像远程过程调用一样完成信息往返。

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











RabbitMQ를 사용하여 PHP에서 분산 메시지 처리를 구현하는 방법 소개: 대규모 애플리케이션 개발에서 분산 시스템은 일반적인 요구 사항이 되었습니다. 분산 메시지 처리는 작업을 여러 처리 노드에 분산하여 시스템의 효율성과 안정성을 향상시키는 패턴입니다. RabbitMQ는 AMQP 프로토콜을 사용하여 메시지 전달 및 처리를 구현하는 신뢰할 수 있는 오픈 소스 메시지 대기열 시스템입니다. 이 기사에서는 배포를 위해 PHP에서 RabbitMQ를 사용하는 방법을 다룹니다.

React 및 RabbitMQ를 사용하여 안정적인 메시징 애플리케이션을 구축하는 방법 소개: 최신 애플리케이션은 실시간 업데이트 및 데이터 동기화와 같은 기능을 달성하기 위해 안정적인 메시징을 지원해야 합니다. React는 사용자 인터페이스 구축을 위한 인기 있는 JavaScript 라이브러리인 반면 RabbitMQ는 안정적인 메시징 미들웨어입니다. 이 기사에서는 React와 RabbitMQ를 결합하여 안정적인 메시징 애플리케이션을 구축하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. RabbitMQ 개요:

최신 애플리케이션의 복잡성이 증가함에 따라 메시징은 강력한 도구가 되었습니다. 이 분야에서 RabbitMQ는 다양한 애플리케이션 간에 메시지를 전달하는 데 사용할 수 있는 매우 인기 있는 메시지 브로커가 되었습니다. 이 기사에서는 Go 언어에서 RabbitMQ를 사용하는 방법을 살펴보겠습니다. 이 가이드에서는 다음 내용을 다룹니다. RabbitMQ 소개 RabbitMQ 설치 RabbitMQ 기본 개념 Go에서 RabbitMQ 시작하기 RabbitMQ 및 Go

메시지가 손실되지 않도록 하는 방법 Rabbitmq 메시지 전달 경로 생산자->스위치->큐->소비자는 일반적으로 세 단계로 나뉩니다. 1. 생산자는 메시지 전달의 신뢰성을 보장합니다. 2.MQ 내부 메시지는 손실되지 않습니다. 3. 소비자 소비가 성공한다. 메시지 전달 신뢰성이란 간단히 말해서 메시지가 메시지 대기열로 100% 전송된다는 의미입니다. verifyCallback을 켤 수 있습니다. 생산자가 메시지를 전달한 후 mq는 ack를 기반으로 메시지가 mq로 전송되었는지 확인할 수 있습니다. #NONE: 비활성화 기본값인 릴리스 확인 모드, 상관 관계:

이제 점점 더 많은 회사들이 마이크로서비스 아키텍처 모델을 채택하기 시작하고 있으며 이 아키텍처에서 메시지 큐는 중요한 통신 방법이 되었으며 그 중 RabbitMQ가 널리 사용됩니다. Go 언어에서 go-zero는 최근 몇 년 동안 등장한 프레임워크로, 개발자가 메시지 대기열을 보다 쉽게 사용할 수 있도록 다양한 실용적인 도구와 방법을 제공합니다. 아래에서는 실제 응용 프로그램을 기반으로 한 go-zero를 소개합니다. RabbitMQ의 응용실습. 1.RabbitMQ 개요Rabbit

Golang과 RabbitMQ 간의 실시간 데이터 동기화 솔루션 소개: 오늘날 인터넷의 대중화와 데이터 양의 폭발적인 증가로 인해 실시간 데이터 동기화가 점점 더 중요해지고 있습니다. 비동기 데이터 전송 및 데이터 동기화 문제를 해결하기 위해 많은 회사에서는 메시지 대기열을 사용하여 데이터의 실시간 동기화를 달성하기 시작했습니다. 이 글에서는 Golang과 RabbitMQ를 기반으로 한 실시간 데이터 동기화 솔루션을 소개하고 구체적인 코드 예시를 제공합니다. 1. RabbitMQ란 무엇인가요? 랍비

GolangRabbitMQ: 고가용성 메시지 대기열 시스템의 아키텍처 설계 및 구현에는 특정 코드 예제가 필요합니다. 소개: 인터넷 기술의 지속적인 발전과 광범위한 응용으로 인해 메시지 대기열은 현대 소프트웨어 시스템에서 없어서는 안될 부분이 되었습니다. 분리, 비동기 통신, 내결함성 처리 및 기타 기능을 구현하는 도구로서 메시지 큐는 분산 시스템에 대한 고가용성 및 확장성 지원을 제공합니다. 효율적이고 간결한 프로그래밍 언어인 Golang은 높은 동시성 및 고성능 시스템을 구축하는 데 널리 사용됩니다.

인터넷 시대의 도래와 함께 메시지 큐 시스템은 점점 더 중요해졌습니다. 이는 서로 다른 애플리케이션 간의 비동기 작업을 가능하게 하고, 결합을 줄이고, 확장성을 향상시켜 전체 시스템의 성능과 사용자 경험을 향상시킵니다. 메시지 큐잉 시스템에서 RabbitMQ는 다양한 메시지 프로토콜을 지원하며 금융 거래, 전자 상거래, 온라인 게임 및 기타 분야에서 널리 사용되는 강력한 오픈 소스 메시지 큐잉 소프트웨어입니다. 실제 애플리케이션에서는 RabbitMQ를 다른 시스템과 통합해야 하는 경우가 많습니다. 이 기사에서는 sw 사용법을 소개합니다.
