Debian Codegraph @

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

raw
1 package main
2
3 import (
4 "context"
5 "fmt"
6 "os"
7 "os/signal"
8 "time"
9
10 "github.com/nats-io/nats.go"
11 "github.com/nats-io/nats.go/jetstream"
12 )
13
14 func main() {
15 // Connect to the NATS server.
16 nc, err := nats.Connect("nats://localhost:4222")
17 if err != nil {
18 panic(err)
19 }
20 defer nc.Close()
21
22 // Create a JetStream context.
23 js, err := jetstream.New(nc)
24 if err != nil {
25 panic(err)
26 }
27
28 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
29 defer cancel()
30
31 // NATS-DOC-START
32 // Bind to the durable "shipping" consumer.
33 cons, err := js.Consumer(ctx, "ORDERS", "shipping")
34 if err != nil {
35 panic(err)
36 }
37
38 // Consume sets up a continuous flow: the library keeps pull requests open
39 // in the background and runs the handler for each order as soon as it lands
40 // in the stream. No fetch loop to write by hand; it runs until you stop it.
41 consCtx, err := cons.Consume(func(msg jetstream.Msg) {
42 fmt.Printf("shipping %s\n", string(msg.Data()))
43 msg.Ack()
44 })
45 if err != nil {
46 panic(err)
47 }
48 defer consCtx.Stop()
49
50 // Keep consuming until interrupted (Ctrl-C).
51 sig := make(chan os.Signal, 1)
52 signal.Notify(sig, os.Interrupt)
53 <-sig
54 // NATS-DOC-END
55 }