Debian Codegraph @

examples/docs/learn-jetstream-worker-pool-worker/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 created earlier.
33 cons, err := js.Consumer(ctx, "ORDERS", "shipping")
34 if err != nil {
35 panic(err)
36 }
37
38 // Consume runs the handler for every order the server hands this worker.
39 // Start this same program in several processes: they all share the one
40 // "shipping" consumer, and the server splits the stored orders across them,
41 // one order to one worker.
42 consCtx, err := cons.Consume(func(msg jetstream.Msg) {
43 fmt.Printf("shipping %s\n", string(msg.Data()))
44 msg.Ack()
45 })
46 if err != nil {
47 panic(err)
48 }
49 defer consCtx.Stop()
50
51 // Keep this worker running until interrupted (Ctrl-C).
52 sig := make(chan os.Signal, 1)
53 signal.Notify(sig, os.Interrupt)
54 <-sig
55 // NATS-DOC-END
56 }