Pular para o conteúdo

Request-Response

RPC sobre mensageria: o cliente envia a requisição e aguarda a resposta numa fila exclusiva, casando o par pelo correlationId.

passos
4
arquivos
6
testes
0
tecnologias
5

Cenário

O portal consulta o saldo da conta ao serviço de saldos pelo RabbitMQ.

Planta

Sequência
4/4
ACC-1001 replyTo=R correlationId=a11entrega2saldo, correlationId=a13resposta do pedido a14Portal (cliente RPC)fila balance-queryServidor de saldosfila de resposta do portal
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

RPC sobre mensageria com fila de resposta exclusiva e par casado pelo correlationId

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    Fila de resposta exclusive e autoDelete

  2. 2

    Consulta em balance-query com replyTo, correlationId e expiration

  3. 3

    O servidor responde em replyTo ecoando o correlationId

  4. 4

    O cliente entrega a resposta ao pedido dono do id

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Servidores escalam competindo pela fila

  • Cliente e servidor não se conhecem

Custos

  • Latência maior que HTTP

  • Cliente precisa de timeout

Código

pattern/messaging/request-response

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 request-response-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 request-response-broker

Saída: portal pergunta por ACC-1001 e recebe a resposta casada pelo correlationId: availableCents 842050.

Requisitos
BunDocker
Sobe junto
RabbitMQ

Código

src/demo.ts

// Demo: the portal asks for a balance over RabbitMQ and waits for the answer on its own reply queue, matched by correlationId.
import amqplib from "amqplib";

const BALANCE_QUERY_QUEUE = "balance-query";
const BALANCE_QUERY_TIMEOUT_MS = 2_000;

const connection = await amqplib.connect(Bun.env.REQUEST_RESPONSE_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
await channel.assertQueue(BALANCE_QUERY_QUEUE, { durable: true });
await channel.purgeQueue(BALANCE_QUERY_QUEUE);

// Server: answers on replyTo and echoes the correlationId so the caller can match the reply.
await channel.consume(BALANCE_QUERY_QUEUE, (message) => {
  if (!message) return;
  const { accountId } = JSON.parse(message.content.toString()) as { accountId: string };
  const reply = { accountId, availableCents: 842_050, queriedAt: new Date().toISOString() };
  channel.sendToQueue(message.properties.replyTo, Buffer.from(JSON.stringify(reply)), { correlationId: message.properties.correlationId });
  channel.ack(message);
});

// Client: exclusive + autoDelete reply queue, which dies with the client instead of leaking in the broker.
const { queue: replyQueue } = await channel.assertQueue("", { exclusive: true, autoDelete: true });
const pending = new Map<string, (body: string) => void>();
await channel.consume(replyQueue, (message) => message && pending.get(message.properties.correlationId)?.(message.content.toString()), { noAck: true });

function balanceGet(accountId: string): Promise<string> {
  const correlationId = crypto.randomUUID();
  return new Promise((resolve) => {
    pending.set(correlationId, resolve);
    // expiration = the caller's patience: a query nobody answered in time is never processed afterwards.
    channel.sendToQueue(BALANCE_QUERY_QUEUE, Buffer.from(JSON.stringify({ accountId })), { replyTo: replyQueue, correlationId, expiration: String(BALANCE_QUERY_TIMEOUT_MS) });
    console.log(`  [PORTAL] asks ${accountId}, correlationId ${correlationId.slice(0, 8)}`);
  });
}

console.log(`  [PORTAL] reply: ${await balanceGet("ACC-1001")}`);
await connection.close();

Nível

introdutório

2/13

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

Domínio financeiro

  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

Infraestrutura

  • RabbitMQmessage broker

    rabbitmq:3-alpine:5672

Variáveis de ambiente

REQUEST_RESPONSE_RABBITMQ_URL
amqp://guest:guest@localhost:5672
RabbitMQ of the balance RPC.

Por que se relacionam

Teste rápido

Qual destes combina com Request-Response?

Próximo projeto, Mensageria & EventosResequencer
Esc

↑ ↓ navegarEnter abrir239 resultados