Debian Codegraph @

examples/docs/learn-jetstream-worker-pool-redelivery-count/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 // Each message carries how many times it has been delivered. A count above
37 // one means a redelivery: the server handed this order out before, but a
38 // worker crashed or ran past AckWait before acking. Key your side effects by
39 // order_id so handling the same order twice is harmless.
40 msgs, err := cons.Fetch(10)
41 if err != nil {
42 panic(err)
43 }
44 for msg := range msgs.Messages() {
45 meta, err := msg.Metadata()
46 if err != nil {
47 panic(err)
48 }
49 if meta.NumDelivered > 1 {
50 fmt.Printf("redelivery #%d of %s\n", meta.NumDelivered, string(msg.Data()))
51 } else {
52 fmt.Printf("first delivery of %s\n", string(msg.Data()))
53 }
54 msg.Ack()
55 }
56 if msgs.Error() != nil {
57 panic(msgs.Error())
58 }
59 // NATS-DOC-END
60 }