pattern/messaging/request-response
- Bun
- RabbitMQ
- TypeScript
- amqplib
- Docker
RPC sobre mensageria: o cliente envia a requisição e aguarda a resposta numa fila exclusiva, casando o par pelo correlationId.
pattern/messaging/request-response
Cenário
O portal consulta o saldo da conta ao serviço de saldos pelo RabbitMQ.
Planta
Sequência4 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.
Vocabulário compartilhado
Fila de resposta exclusive e autoDelete
Consulta em balance-query com replyTo, correlationId e expiration
O servidor responde em replyTo ecoando o correlationId
O cliente entrega a resposta ao pedido dono do id
Trade-offs
O que se ganha, o que se paga
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./
src/
Executar com Docker
./docker.shuntil docker exec --user rabbitmq request-response-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f request-response-brokerSaída: portal pergunta por ACC-1001 e recebe a resposta casada pelo correlationId: availableCents 842050.
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
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
RabbitMQmessage broker
rabbitmq:3-alpine:5672
Variáveis de ambiente
Por que se relacionam
Teste rápido
Qual destes combina com Request-Response?
replyTo e correlationId. Abrir RabbitMQ
Seu progresso
0/157 estudados
Fica salvo só neste navegador.