Подробно о pull-потребителях
shipping выдаёт сообщение по запросу обработчика — pull. Ранее это означало «дай одно сообщение».
Но можно запросить несколько, обработать и вернуться либо получать непрерывно по мере поступления. Разберём оба шаблона и их ограничения.
shipping остаётся pull с явным ack. Меняется управляющий клиентский код.
Два способа запроса
Библиотеки называют их одинаково.
Fetch запрашивает до N сообщений и завершает пакет при заполнении или тайм-ауте. Обработайте конечный набор и при необходимости повторите вызов.
Consume поддерживает непрерывный поток. Переданная функция вызывается для каждого сообщения, библиотека фоном обновляет pull-запросы до вашей остановки.
Fetch удобен для контролируемых раундов, cron и небольших выборок обработчика запроса. Consume — для длительного сервиса, работающего по мере поступления; его используют большинство сервисов.
Получение пакета
Укажите размер и тайм-аут: до десяти сообщений за две секунды.
- CLI
- JavaScript/TypeScript
- Go
- Python
- Java
- Rust
- C#/.NET
- C
#!/bin/bash
# Fetch a batch of up to 10 messages from the shipping pull consumer,
# waiting up to 2 seconds for them. nats consumer next is a single
# fetch; --count is the batch size, --wait is the timeout.
nats consumer next ORDERS shipping --count 10 --wait 2s
// Bind to the durable "shipping" consumer.
const js = jetstream(nc);
const c = await js.consumers.get("ORDERS", "shipping");
// Fetch a batch of up to 10 orders, waiting up to 2 seconds for them. The call
// returns when the batch is full or the wait elapses, whichever comes first.
// Process and ack each, then fetch again to keep going.
const msgs = await c.fetch({ max_messages: 10, expires: 2000 });
for await (const m of msgs) {
console.log(`shipping ${m.string()}`);
m.ack();
}
// Bind to the durable "shipping" consumer.
cons, err := js.Consumer(ctx, "ORDERS", "shipping")
if err != nil {
panic(err)
}
// Fetch a batch of up to 10 orders, waiting up to 2 seconds for them. The
// call returns when the batch is full or the wait elapses, whichever comes
// first. Process and ack each one, then fetch again to keep going.
msgs, err := cons.Fetch(10, jetstream.FetchMaxWait(2*time.Second))
if err != nil {
panic(err)
}
for msg := range msgs.Messages() {
fmt.Printf("shipping %s\n", string(msg.Data()))
msg.Ack()
}
if msgs.Error() != nil {
panic(msgs.Error())
}
# Bind to the durable "shipping" consumer.
psub = await js.pull_subscribe_bind("shipping", stream="ORDERS")
# Fetch a batch of up to 10 orders, waiting up to 2 seconds for them. The
# call returns the messages it has when the batch is full or the timeout
# passes. Process and ack each, then fetch again to keep going.
msgs = await psub.fetch(batch=10, timeout=2)
for msg in msgs:
print(f"shipping {msg.data.decode()}")
await msg.ack()
// Fetch a batch of up to 10 orders, waiting up to 2 seconds for
// them. The fetch ends when the batch is full or the wait elapses,
// whichever comes first. Process and ack each, then fetch again.
try (FetchConsumer fc = cc.fetch(
FetchConsumeOptions.builder().maxMessages(10).expiresIn(2000).build())) {
Message m;
while ((m = fc.nextMessage()) != null) {
System.out.println("shipping " + new String(m.getData(), StandardCharsets.UTF_8));
m.ack();
}
}
// Bind to the durable "shipping" consumer.
let stream = js.get_stream("ORDERS").await?;
let consumer: PullConsumer = stream.get_consumer("shipping").await?;
// Fetch a batch of up to 10 orders, waiting up to 2 seconds for them. The
// call returns when the batch is full or the wait elapses, whichever comes
// first. Process and ack each, then fetch again to keep going.
let mut messages = consumer
.fetch()
.max_messages(10)
.expires(Duration::from_secs(2))
.messages()
.await?;
while let Some(msg) = messages.next().await {
let msg = msg?;
println!("shipping {}", std::str::from_utf8(&msg.payload)?);
msg.ack().await?;
}
// Bind to the durable "shipping" consumer.
var consumer = await js.GetConsumerAsync("ORDERS", "shipping");
// Fetch a batch of up to 10 orders, waiting up to 2 seconds for them. The
// call returns the messages it has when the batch is full or the wait
// elapses. Process and ack each, then fetch again to keep going.
await foreach (var msg in consumer.FetchAsync<Order>(
opts: new NatsJSFetchOpts { MaxMsgs = 10, Expires = TimeSpan.FromSeconds(2) }))
{
output.WriteLine($"shipping {msg.Data}");
await msg.AckAsync();
shipped++;
}
// Bind to the durable "shipping" consumer.
jsSubOptions so;
jsSubOptions_Init(&so);
so.Stream = "ORDERS";
so.Consumer = "shipping";
s = js_PullSubscribe(&sub, js, NULL, NULL, NULL, &so, &jerr);
if (s == NATS_OK)
{
// Fetch a batch of up to 10 orders, waiting up to 2 seconds for
// them. The call returns when the batch is full or the wait
// elapses, whichever comes first. Process and ack each one, then
// fetch again to keep going.
natsMsgList list = {NULL, 0};
s = natsSubscription_Fetch(&list, sub, 10, 2000, &jerr);
if ((s == NATS_OK) || (s == NATS_TIMEOUT))
{
for (int i = 0; i < list.Count; i++)
{
printf("shipping %s\n", natsMsg_GetData(list.Msgs[i]));
natsMsg_Ack(list.Msgs[i], NULL);
}
natsMsgList_Destroy(&list);
s = NATS_OK;
}
}
Нормальны два результата.
Если накоплено десять, они выдаются сразу; обработчик подтверждает и повторяет.
Если есть три, они поступят, а оставшееся время запрос подождёт новых до двух секунд. После истечения пакет завершится с тремя.
CLI не делает один пакетный запрос: nats consumer next --count N выполняет N одиночных pull подряд, каждый со своим --timeout. Это приближение цикла fetch:
- CLI
#!/bin/bash
# A CLI fetch. --count retrieves up to 5 messages by issuing 5 single
# pulls in a row, not one batch request. Run this again to walk the
# stream a batch at a time.
nats consumer next ORDERS shipping --count 5
Повторяйте для чтения порциями. Позиция подтверждения продвигается так же, как при одиночных запросах.
Непрерывное потребление
Для длительного обработчика используйте consume вместо ручного цикла fetch. Запросы остаются открытыми для немедленной доставки новых записей:
- CLI
- JavaScript/TypeScript
- Go
- Python
- Java
- Rust
- C#/.NET
- C
#!/bin/bash
# Consume a continuous flow from the CLI. nats consumer next exits after
# --timeout of quiet, so wrap it in a loop to keep going as new messages
# land. --ack acknowledges each message as it is received. Ctrl-C stops
# the loop.
while true; do
nats consumer next ORDERS shipping --count 100 --ack --timeout 5s || sleep 1
done
// Bind to the durable "shipping" consumer.
const js = jetstream(nc);
const c = await js.consumers.get("ORDERS", "shipping");
// consume() sets up a continuous flow: the library keeps pull requests open and
// yields each order as soon as it lands in the stream. It runs until you stop
// it, no fetch loop to write by hand.
const messages = await c.consume();
for await (const m of messages) {
console.log(`shipping ${m.string()}`);
m.ack();
}
// Bind to the durable "shipping" consumer.
cons, err := js.Consumer(ctx, "ORDERS", "shipping")
if err != nil {
panic(err)
}
// Consume sets up a continuous flow: the library keeps pull requests open
// in the background and runs the handler for each order as soon as it lands
// in the stream. No fetch loop to write by hand; it runs until you stop it.
consCtx, err := cons.Consume(func(msg jetstream.Msg) {
fmt.Printf("shipping %s\n", string(msg.Data()))
msg.Ack()
})
if err != nil {
panic(err)
}
defer consCtx.Stop()
// Keep consuming until interrupted (Ctrl-C).
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
# Bind to the durable "shipping" consumer.
psub = await js.pull_subscribe_bind("shipping", stream="ORDERS")
# nats.py drives a pull consumer with fetch, so a continuous flow is a fetch
# loop: pull a batch, process it, come back. fetch times out when nothing is
# waiting; keep looping so new orders are picked up as soon as they land.
while True:
try:
msgs = await psub.fetch(batch=10, timeout=5)
except nats.errors.TimeoutError:
continue
for msg in msgs:
print(f"shipping {msg.data.decode()}")
await msg.ack()
// consume() sets up a continuous flow: the library keeps pull
// requests open and runs the handler for each order as soon as it
// lands in the stream. It runs until you stop it.
try (MessageConsumer mc = cc.consume(msg -> {
System.out.println("shipping " + new String(msg.getData(), StandardCharsets.UTF_8));
msg.ack();
})) {
// Keep consuming until the process is stopped.
Thread.sleep(Long.MAX_VALUE);
}
// Bind to the durable "shipping" consumer.
let stream = js.get_stream("ORDERS").await?;
let consumer: PullConsumer = stream.get_consumer("shipping").await?;
// messages() sets up a continuous flow: the library keeps pull requests
// open and yields each order as soon as it lands in the stream. It runs
// until you stop it, no fetch loop to write by hand.
let mut messages = consumer.messages().await?;
while let Some(msg) = messages.next().await {
let msg = msg?;
println!("shipping {}", std::str::from_utf8(&msg.payload)?);
msg.ack().await?;
}
// Bind to the durable "shipping" consumer.
var consumer = await js.GetConsumerAsync("ORDERS", "shipping");
// ConsumeAsync sets up a continuous flow: it keeps pull requests open and
// yields each order as soon as it lands in the stream. It runs until you
// stop it, no fetch loop to write by hand.
await foreach (var msg in consumer.ConsumeAsync<Order>())
{
output.WriteLine($"shipping {msg.Data}");
await msg.AckAsync();
// A real consumer runs forever; stop once the backlog is clear so the
// example returns.
if (++shipped == 2)
{
break;
}
}
// The handler runs for each order as soon as it lands in the stream.
static void
onOrder(natsConnection *nc, natsSubscription *sub, natsMsg *msg, void *closure)
{
printf("shipping %s\n", natsMsg_GetData(msg));
natsMsg_Ack(msg, NULL);
natsMsg_Destroy(msg);
}
// Bind to the durable "shipping" consumer. The library keeps pull
// requests open in the background and dispatches messages to the
// handler. No fetch loop to write by hand; it runs until you stop it.
jsSubOptions so;
jsSubOptions_Init(&so);
so.Stream = "ORDERS";
so.Consumer = "shipping";
so.ManualAck = true;
s = js_PullSubscribeAsync(&sub, js, NULL, NULL,
onOrder, NULL, NULL, &so, &jerr);
Функция обрабатывает и подтверждает сообщение. Библиотека восполняет запросы до остановки. Это обычный шаблон обработки заказов.
Два ограничения pull
Оба способа используют один протокольный запрос с полями:
- batch — максимум сообщений. Большой пакет сокращает обмены и повышает скорость; маленький уменьшает задержку и объём незавершённой работы при падении.
- expires — сколько сервер ждёт сообщения перед завершением запроса. Ограничивает ожидание тихого потока.
Библиотеки задают стандартные значения и автоматически поддерживают batch и expires для consume.
Все поля — в Справочнике → Следующее сообщение. Здесь нужны только batch и expires.
Типичные ошибки
При реальном трафике учтите несколько настроек.
Пустой fetch нормален. При истечении expires без заказов приходит 408 Request Timeout, а для no-wait — 404 No Messages. Библиотеки сообщают пустой пакет, CLI завершает с ненулевым кодом. Это отсутствие данных сейчас, не поломка: ждите и продолжайте.
- CLI
- JavaScript/TypeScript
- Go
- Python
- Java
- Rust
- C#/.NET
- C
#!/bin/bash
# A fetch on a drained consumer returns nothing. nats consumer next exits
# non-zero when the pull times out with no messages waiting. Treat that as
# "nothing right now," not a failure: sleep and fetch again.
if nats consumer next ORDERS shipping --count 10 --timeout 2s; then
echo "processed a batch"
else
echo "no orders waiting, will retry"
sleep 1
fi
// Bind to the durable "shipping" consumer.
const js = jetstream(nc);
const c = await js.consumers.get("ORDERS", "shipping");
// A fetch on a drained consumer ends empty once the wait elapses, not with an
// error. Treat "nothing right now" as normal: if no orders came back, wait and
// fetch again instead of failing.
const msgs = await c.fetch({ max_messages: 10, expires: 2000 });
let count = 0;
for await (const m of msgs) {
console.log(`shipping ${m.string()}`);
m.ack();
count++;
}
if (count === 0) {
console.log("no orders waiting, will retry");
}
// Bind to the durable "shipping" consumer.
cons, err := js.Consumer(ctx, "ORDERS", "shipping")
if err != nil {
panic(err)
}
// A fetch on a drained consumer returns an empty batch once the wait
// elapses, not an error. Treat "nothing right now" as normal: if no orders
// came back, wait and fetch again instead of failing.
msgs, err := cons.Fetch(10, jetstream.FetchMaxWait(2*time.Second))
if err != nil {
panic(err)
}
count := 0
for msg := range msgs.Messages() {
fmt.Printf("shipping %s\n", string(msg.Data()))
msg.Ack()
count++
}
if msgs.Error() != nil {
panic(msgs.Error())
}
if count == 0 {
fmt.Println("no orders waiting, will retry")
time.Sleep(time.Second)
}
# Bind to the durable "shipping" consumer.
psub = await js.pull_subscribe_bind("shipping", stream="ORDERS")
# On a drained consumer, fetch raises TimeoutError once the timeout passes.
# Treat that as "nothing right now," not a failure: catch it, wait, and
# fetch again instead of crashing.
try:
msgs = await psub.fetch(batch=10, timeout=2)
except nats.errors.TimeoutError:
print("no orders waiting, will retry")
msgs = []
for msg in msgs:
print(f"shipping {msg.data.decode()}")
await msg.ack()
// On a drained consumer the fetch ends with no messages once the
// expiry passes, and nextMessage() returns null right away. Treat
// that as "nothing right now," not a failure: note it and fetch
// again instead of erroring.
try (FetchConsumer fc = cc.fetch(
FetchConsumeOptions.builder().maxMessages(10).expiresIn(2000).build())) {
Message m = fc.nextMessage();
if (m == null) {
System.out.println("no orders waiting, will retry");
}
while (m != null) {
System.out.println("shipping " + new String(m.getData(), StandardCharsets.UTF_8));
m.ack();
m = fc.nextMessage();
}
}
// Bind to the durable "shipping" consumer.
let stream = js.get_stream("ORDERS").await?;
let consumer: PullConsumer = stream.get_consumer("shipping").await?;
// A fetch on a drained consumer ends empty once the wait elapses, not with
// an error. Treat "nothing right now" as normal: if no orders came back,
// wait and fetch again instead of failing.
let mut messages = consumer
.fetch()
.max_messages(10)
.expires(Duration::from_secs(2))
.messages()
.await?;
let mut count = 0;
while let Some(msg) = messages.next().await {
let msg = msg?;
println!("shipping {}", std::str::from_utf8(&msg.payload)?);
msg.ack().await?;
count += 1;
}
if count == 0 {
println!("no orders waiting, will retry");
}
// Bind to the durable "shipping" consumer.
var consumer = await js.GetConsumerAsync("ORDERS", "shipping");
// On a drained consumer the fetch ends with no messages once the expiry
// passes, not with an error. Treat "nothing right now" as normal: if no
// orders came back, wait and fetch again instead of failing.
await foreach (var msg in consumer.FetchAsync<string>(
opts: new NatsJSFetchOpts { MaxMsgs = 10, Expires = TimeSpan.FromSeconds(2) }))
{
output.WriteLine($"shipping {msg.Data}");
await msg.AckAsync();
shipped++;
}
if (shipped == 0)
{
output.WriteLine("no orders waiting, will retry");
}
// Bind to the durable "shipping" consumer.
jsSubOptions so;
jsSubOptions_Init(&so);
so.Stream = "ORDERS";
so.Consumer = "shipping";
s = js_PullSubscribe(&sub, js, NULL, NULL, NULL, &so, &jerr);
if (s == NATS_OK)
{
// A fetch on a drained consumer comes back empty with
// NATS_TIMEOUT once the wait elapses. Treat "nothing right now"
// as normal: if no orders came back, wait and fetch again
// instead of failing.
natsMsgList list = {NULL, 0};
s = natsSubscription_Fetch(&list, sub, 10, 2000, &jerr);
if ((s == NATS_OK) || (s == NATS_TIMEOUT))
{
for (int i = 0; i < list.Count; i++)
{
printf("shipping %s\n", natsMsg_GetData(list.Msgs[i]));
natsMsg_Ack(list.Msgs[i], NULL);
}
if (list.Count == 0)
{
printf("no orders waiting, will retry\n");
nats_Sleep(1000);
}
natsMsgList_Destroy(&list);
s = NATS_OK;
}
}
Сырой запрос без expires может ждать бесконечно. Нулевой expires ждёт полного пакета. Библиотеки защищают стандартным сроком около 30 секунд; при нужном пределе задавайте явно. CLI использует --timeout.
Малый MaxAckPending ограничивает скорость. При лимите десять и пакете сто сервер выдаст десять и будет ждать ack. Держите предел не ниже пакета; стандарт — 1000. Он общий для всех обработчиков пула.
Большой пакет расходует память. batch считает сообщения, не байты. Для крупных заказов ограничивайте также max_bytes в fetch или consume: запрос завершится по первому достигнутому пределу.
Что уже готово
У ORDERS и shipping прежнее устройство. Вы умеете получать конечный пакет или непрерывный поток, ограничивая pull через batch и expires.
Что дальше
Добавим несколько обработчиков одного shipping с общей позицией. Общий для всех MaxAckPending становится особенно важен.
См. также
- Справочник → Следующее сообщение — включая
no_waitиmin_pending. - Пул обработчиков — несколько клиентов одного pull-потребителя.