| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"fmt" |
| 6 |
"time" |
| 7 |
|
| 8 |
"github.com/nats-io/nats.go" |
| 9 |
"github.com/nats-io/nats.go/jetstream" |
| 10 |
) |
| 11 |
|
| 12 |
func main() { |
| 13 |
// Connect to the NATS server. |
| 14 |
nc, err := nats.Connect("nats://localhost:4222") |
| 15 |
if err != nil { |
| 16 |
panic(err) |
| 17 |
} |
| 18 |
defer nc.Close() |
| 19 |
|
| 20 |
// Create a JetStream context (the stream manager). |
| 21 |
js, err := jetstream.New(nc) |
| 22 |
if err != nil { |
| 23 |
panic(err) |
| 24 |
} |
| 25 |
|
| 26 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 27 |
defer cancel() |
| 28 |
|
| 29 |
// NATS-DOC-START |
| 30 |
// Create a durable pull consumer named "analytics-typo" on the ORDERS |
| 31 |
// stream. The filter "orders.shiped" has a typo (one "p"), so it matches |
| 32 |
// no subject the stream actually stores. |
| 33 |
cons, err := js.CreateOrUpdateConsumer(ctx, "ORDERS", jetstream.ConsumerConfig{ |
| 34 |
Durable: "analytics-typo", |
| 35 |
FilterSubject: "orders.shiped", |
| 36 |
DeliverPolicy: jetstream.DeliverAllPolicy, |
| 37 |
AckPolicy: jetstream.AckExplicitPolicy, |
| 38 |
}) |
| 39 |
if err != nil { |
| 40 |
panic(err) |
| 41 |
} |
| 42 |
|
| 43 |
// Fetch with a short expiry. The fetch succeeds with no error, but the |
| 44 |
// channel yields zero messages because the filter matched no stored subject. |
| 45 |
msgs, err := cons.Fetch(5, jetstream.FetchMaxWait(2*time.Second)) |
| 46 |
if err != nil { |
| 47 |
panic(err) |
| 48 |
} |
| 49 |
count := 0 |
| 50 |
for range msgs.Messages() { |
| 51 |
count++ |
| 52 |
} |
| 53 |
if err := msgs.Error(); err != nil { |
| 54 |
panic(err) |
| 55 |
} |
| 56 |
|
| 57 |
// A wrong filter fails silently: the pull returned nothing, and no error |
| 58 |
// was raised. The consumer is healthy, it just never matches a message. |
| 59 |
fmt.Printf("Received %d messages: the filter matched no stored subject, so the pull returned nothing (no error).\n", count) |
| 60 |
// NATS-DOC-END |
| 61 |
} |