Pular para o conteúdo

Message Routing

O produtor diz o que aconteceu na routing key; o broker entrega cópias às filas cujo binding casa. Use quando consumidores querem fatias diferentes do mesmo fluxo.

passos
4
arquivos
6
testes
0
tecnologias
5

Cenário

PIX e TED publicados; cada trilho recebe só a sua operação e a auditoria recebe as duas.

Planta

Fluxo
4/4
Produtorbank.operations (topic)operation-pixoperation-tedoperation-auditpayment.pix.*payment.ted.*payment.#
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

O produtor diz o que aconteceu na routing key e o broker entrega cópias às filas cujo binding casa

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

domínio.subtipo.estado+1
  1. 1

    Routing key domínio.subtipo.estado

  2. 2

    * casa uma palavra, # zero ou mais

  3. 3

    Cópia para cada binding que casa

  4. 4

    Novo consumidor = novo binding

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Produtor não conhece destinos

  • Novo consumidor sem tocar no produtor

Custos

  • Regras espalhadas nos bindings

  • Chave sem binding some sem alerta

Código

pattern/messaging/message-routing

6 arquivos

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec --user rabbitmq message-routing-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f message-routing-broker

Saída: OP-001 (PIX) em operation-pix, OP-002 (TED) em operation-ted; operation-audit recebe as duas.

Requisitos
BunDocker
Sobe junto
RabbitMQ

Código

src/demo.ts

// Demo: the producer only names the fact in the routing key; the topic exchange decides which queues get a copy.
import amqplib, { type Channel } from "amqplib";

const OPERATION_EXCHANGE = "bank.operations";
// `*` is exactly one word, `#` is zero or more; a message goes to every binding that matches.
const OPERATION_BINDINGS = { "operation-pix": "payment.pix.*", "operation-ted": "payment.ted.*", "operation-audit": "payment.#" };

const connection = await amqplib.connect(Bun.env.MESSAGE_ROUTING_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
await channel.assertExchange(OPERATION_EXCHANGE, "topic", { durable: true });
for (const [queue, pattern] of Object.entries(OPERATION_BINDINGS)) {
  await channel.assertQueue(queue, { durable: true });
  await channel.bindQueue(queue, OPERATION_EXCHANGE, pattern);
  await channel.purgeQueue(queue);
}

for (const [routingKey, operationId] of [["payment.pix.approved", "OP-001"], ["payment.ted.approved", "OP-002"]]) {
  channel.publish(OPERATION_EXCHANGE, routingKey!, Buffer.from(JSON.stringify({ operationId, amountCents: 150_000 })), { persistent: true });
  console.log(`  [PUBLISH] ${operationId} ${routingKey}`);
}
await Bun.sleep(200);

// Drains each queue to show where the broker routed each copy.
async function queueDrain(queueChannel: Channel, queue: string): Promise<string[]> {
  const found: string[] = [];
  for (let message = await queueChannel.get(queue, { noAck: true }); message; message = await queueChannel.get(queue, { noAck: true })) {
    found.push(`${(JSON.parse(message.content.toString()) as { operationId: string }).operationId} (${message.fields.routingKey})`);
  }
  return found;
}

for (const queue of Object.keys(OPERATION_BINDINGS)) console.log(`  [ROUTED] ${queue.padEnd(16)} ${(await queueDrain(channel, queue)).join(", ")}`);
await connection.close();

Nível

introdutório

2/13

Linhas de TypeScript
28
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • PIX
  • TED

Padrões do catálogo que implementa

  • Message Routing

Infraestrutura

  • RabbitMQmessage broker

    rabbitmq:3-alpine:5672

Variáveis de ambiente

MESSAGE_ROUTING_RABBITMQ_URL
amqp://guest:guest@localhost:5672
RabbitMQ of the bank operations.

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Message Routing?

Próximo projeto, Mensageria & EventosMessaging Bridge
Esc

↑ ↓ navegarEnter abrir239 resultados