Debian Codegraph @

examples/docs/learn-jetstream-pull-consumers-emptyFetch/main.go

raw
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.
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 // Bind to the durable "shipping" consumer.
31 cons, err := js.Consumer(ctx, "ORDERS", "shipping")
32 if err != nil {
33 panic(err)
34 }
35
36 // A fetch on a drained consumer returns an empty batch once the wait
37 // elapses, not an error. Treat "nothing right now" as normal: if no orders
38 // came back, wait and fetch again instead of failing.
39 msgs, err := cons.Fetch(10, jetstream.FetchMaxWait(2*time.Second))
40 if err != nil {
41 panic(err)
42 }
43 count := 0
44 for msg := range msgs.Messages() {
45 fmt.Printf("shipping %s\n", string(msg.Data()))
46 msg.Ack()
47 count++
48 }
49 if msgs.Error() != nil {
50 panic(msgs.Error())
51 }
52 if count == 0 {
53 fmt.Println("no orders waiting, will retry")
54 time.Sleep(time.Second)
55 }
56 // NATS-DOC-END
57 }