Debian Codegraph @

examples/docs/learn-jetstream-get-direct-direct-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 (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 // Look up the ORDERS stream. The handle caches the stream config, including
30 // AllowDirect, which must already be enabled on the stream.
31 stream, err := js.Stream(ctx, "ORDERS")
32 if err != nil {
33 panic(err)
34 }
35
36 // NATS-DOC-START
37 // Read the message at sequence 1. Because the stream has AllowDirect
38 // enabled, GetMsg is served by the Direct Get API, so any replica can
39 // answer it, not only the leader.
40 msg, err := stream.GetMsg(ctx, 1)
41 if err != nil {
42 panic(err)
43 }
44
45 fmt.Printf("Subject: %s\n", msg.Subject)
46 fmt.Printf("Payload: %s\n", string(msg.Data))
47 // NATS-DOC-END
48 }