Debian Codegraph @

examples/nats-qsub/main.go

raw
1 // Copyright 2012-2022 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package main
15
16 import (
17 "flag"
18 "log"
19 "os"
20 "os/signal"
21 "time"
22
23 "github.com/nats-io/nats.go"
24 )
25
26 // NOTE: Can test with demo servers.
27 // nats-qsub -s demo.nats.io <subject> <queue>
28
29 func usage() {
30 log.Printf("Usage: nats-qsub [-s server] [-creds file] [-nkey file] [-t] <subject> <queue>\n")
31 flag.PrintDefaults()
32 }
33
34 func showUsageAndExit(exitcode int) {
35 usage()
36 os.Exit(exitcode)
37 }
38
39 func printMsg(m *nats.Msg, i int) {
40 log.Printf("[#%d] Received on [%s] Queue[%s] Pid[%d]: '%s'", i, m.Subject, m.Sub.Queue, os.Getpid(), string(m.Data))
41 }
42
43 func main() {
44 var urls = flag.String("s", nats.DefaultURL, "The nats server URLs (separated by comma)")
45 var userCreds = flag.String("creds", "", "User Credentials File")
46 var nkeyFile = flag.String("nkey", "", "NKey Seed File")
47 var showTime = flag.Bool("t", false, "Display timestamps")
48 var showHelp = flag.Bool("h", false, "Show help message")
49
50 log.SetFlags(0)
51 flag.Usage = usage
52 flag.Parse()
53
54 if *showHelp {
55 showUsageAndExit(0)
56 }
57
58 args := flag.Args()
59 if len(args) != 2 {
60 showUsageAndExit(1)
61 }
62
63 // Connect Options.
64 opts := []nats.Option{nats.Name("NATS Sample Queue Subscriber")}
65 opts = setupConnOptions(opts)
66
67 if *userCreds != "" && *nkeyFile != "" {
68 log.Fatal("specify -seed or -creds")
69 }
70
71 // Use UserCredentials
72 if *userCreds != "" {
73 opts = append(opts, nats.UserCredentials(*userCreds))
74 }
75
76 // Use Nkey authentication.
77 if *nkeyFile != "" {
78 opt, err := nats.NkeyOptionFromSeed(*nkeyFile)
79 if err != nil {
80 log.Fatal(err)
81 }
82 opts = append(opts, opt)
83 }
84
85 // Connect to NATS
86 nc, err := nats.Connect(*urls, opts...)
87 if err != nil {
88 log.Fatal(err)
89 }
90
91 subj, queue, i := args[0], args[1], 0
92
93 nc.QueueSubscribe(subj, queue, func(msg *nats.Msg) {
94 i++
95 printMsg(msg, i)
96 })
97 nc.Flush()
98
99 if err := nc.LastError(); err != nil {
100 log.Fatal(err)
101 }
102
103 log.Printf("Listening on [%s], queue group [%s]", subj, queue)
104 if *showTime {
105 log.SetFlags(log.LstdFlags)
106 }
107
108 // Setup the interrupt handler to drain so we don't miss
109 // requests when scaling down.
110 c := make(chan os.Signal, 1)
111 signal.Notify(c, os.Interrupt)
112 <-c
113 log.Println()
114 log.Printf("Draining...")
115 nc.Drain()
116 log.Fatalf("Exiting")
117 }
118
119 func setupConnOptions(opts []nats.Option) []nats.Option {
120 totalWait := 10 * time.Minute
121 reconnectDelay := time.Second
122
123 opts = append(opts, nats.ReconnectWait(reconnectDelay))
124 opts = append(opts, nats.MaxReconnects(int(totalWait/reconnectDelay)))
125 opts = append(opts, nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
126 log.Printf("Disconnected due to: %s, will attempt reconnects for %.0fm", err, totalWait.Minutes())
127 }))
128 opts = append(opts, nats.ReconnectHandler(func(nc *nats.Conn) {
129 log.Printf("Reconnected [%s]", nc.ConnectedUrl())
130 }))
131 opts = append(opts, nats.ClosedHandler(func(nc *nats.Conn) {
132 log.Fatalf("Exiting: %v", nc.LastError())
133 }))
134 return opts
135 }