Debian Codegraph @

examples/docs/learn-jetstream-ordered-consumer-read/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 // Ask for an ordered consumer over the stream. There's no name to manage and
31 // no ack to send: the library runs the consumer for you and recreates it if
32 // it ever misses a message, so you read every order in stream order. An
33 // empty config starts from the first order.
34 cons, err := js.OrderedConsumer(ctx, "ORDERS", jetstream.OrderedConsumerConfig{})
35 if err != nil {
36 panic(err)
37 }
38
39 iter, err := cons.Messages()
40 if err != nil {
41 panic(err)
42 }
43 defer iter.Stop()
44
45 // Read the whole log once, in order, stopping when caught up (NumPending 0).
46 for {
47 msg, err := iter.Next()
48 if err != nil {
49 break
50 }
51 meta, err := msg.Metadata()
52 if err != nil {
53 panic(err)
54 }
55 fmt.Printf("order %s\n", string(msg.Data()))
56 if meta.NumPending == 0 {
57 break
58 }
59 }
60 // NATS-DOC-END
61 }