Debian Codegraph @

example_test.go

raw
1 // Copyright 2012-2023 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 nats_test
15
16 import (
17 "context"
18 "fmt"
19 "log"
20 "net"
21 "time"
22
23 "github.com/nats-io/nats.go"
24 )
25
26 // Shows different ways to create a Conn.
27 func ExampleConnect() {
28 nc, _ := nats.Connect("demo.nats.io")
29 nc.Close()
30
31 nc, _ = nats.Connect("nats://derek:[email protected]:4222")
32 nc.Close()
33
34 nc, _ = nats.Connect("tls://derek:[email protected]:4443")
35 nc.Close()
36
37 opts := nats.Options{
38 AllowReconnect: true,
39 MaxReconnect: 10,
40 ReconnectWait: 5 * time.Second,
41 Timeout: 1 * time.Second,
42 }
43
44 nc, _ = opts.Connect()
45 nc.Close()
46 }
47
48 type skipTLSDialer struct {
49 dialer *net.Dialer
50 skipTLS bool
51 }
52
53 func (sd *skipTLSDialer) Dial(network, address string) (net.Conn, error) {
54 return sd.dialer.Dial(network, address)
55 }
56
57 func (sd *skipTLSDialer) SkipTLSHandshake() bool {
58 return sd.skipTLS
59 }
60
61 func ExampleCustomDialer() {
62 // Given the following CustomDialer implementation:
63 //
64 // type skipTLSDialer struct {
65 // dialer *net.Dialer
66 // skipTLS bool
67 // }
68 //
69 // func (sd *skipTLSDialer) Dial(network, address string) (net.Conn, error) {
70 // return sd.dialer.Dial(network, address)
71 // }
72 //
73 // func (sd *skipTLSDialer) SkipTLSHandshake() bool {
74 // return true
75 // }
76 //
77 sd := &skipTLSDialer{dialer: &net.Dialer{Timeout: 2 * time.Second}, skipTLS: true}
78 nc, _ := nats.Connect("demo.nats.io", nats.SetCustomDialer(sd))
79 defer nc.Close()
80 }
81
82 // This Example shows an asynchronous subscriber.
83 func ExampleConn_Subscribe() {
84 nc, _ := nats.Connect(nats.DefaultURL)
85 defer nc.Close()
86
87 nc.Subscribe("foo", func(m *nats.Msg) {
88 fmt.Printf("Received a message: %s\n", string(m.Data))
89 })
90 }
91
92 func ExampleConn_ForceReconnect() {
93 nc, _ := nats.Connect(nats.DefaultURL)
94 defer nc.Close()
95
96 nc.Subscribe("foo", func(m *nats.Msg) {
97 fmt.Printf("Received a message: %s\n", string(m.Data))
98 })
99
100 // Reconnect to the server.
101 // the subscription will be recreated after the reconnect.
102 nc.ForceReconnect()
103 }
104
105 // This Example shows a synchronous subscriber.
106 func ExampleConn_SubscribeSync() {
107 nc, _ := nats.Connect(nats.DefaultURL)
108 defer nc.Close()
109
110 sub, _ := nc.SubscribeSync("foo")
111 m, err := sub.NextMsg(1 * time.Second)
112 if err == nil {
113 fmt.Printf("Received a message: %s\n", string(m.Data))
114 } else {
115 fmt.Println("NextMsg timed out.")
116 }
117 }
118
119 func ExampleSubscription_NextMsg() {
120 nc, _ := nats.Connect(nats.DefaultURL)
121 defer nc.Close()
122
123 sub, _ := nc.SubscribeSync("foo")
124 m, err := sub.NextMsg(1 * time.Second)
125 if err == nil {
126 fmt.Printf("Received a message: %s\n", string(m.Data))
127 } else {
128 fmt.Println("NextMsg timed out.")
129 }
130 }
131
132 func ExampleSubscription_Unsubscribe() {
133 nc, _ := nats.Connect(nats.DefaultURL)
134 defer nc.Close()
135
136 sub, _ := nc.SubscribeSync("foo")
137 // ...
138 sub.Unsubscribe()
139 }
140
141 func ExampleConn_Publish() {
142 nc, _ := nats.Connect(nats.DefaultURL)
143 defer nc.Close()
144
145 nc.Publish("foo", []byte("Hello World!"))
146 }
147
148 func ExampleConn_PublishMsg() {
149 nc, _ := nats.Connect(nats.DefaultURL)
150 defer nc.Close()
151
152 msg := &nats.Msg{Subject: "foo", Reply: "bar", Data: []byte("Hello World!")}
153 nc.PublishMsg(msg)
154 }
155
156 func ExampleConn_Flush() {
157 nc, _ := nats.Connect(nats.DefaultURL)
158 defer nc.Close()
159
160 msg := &nats.Msg{Subject: "foo", Reply: "bar", Data: []byte("Hello World!")}
161 for i := 0; i < 1000; i++ {
162 nc.PublishMsg(msg)
163 }
164 err := nc.Flush()
165 if err == nil {
166 // Everything has been processed by the server for nc *Conn.
167 }
168 }
169
170 func ExampleConn_FlushTimeout() {
171 nc, _ := nats.Connect(nats.DefaultURL)
172 defer nc.Close()
173
174 msg := &nats.Msg{Subject: "foo", Reply: "bar", Data: []byte("Hello World!")}
175 for i := 0; i < 1000; i++ {
176 nc.PublishMsg(msg)
177 }
178 // Only wait for up to 1 second for Flush
179 err := nc.FlushTimeout(1 * time.Second)
180 if err == nil {
181 // Everything has been processed by the server for nc *Conn.
182 }
183 }
184
185 func ExampleConn_Request() {
186 nc, _ := nats.Connect(nats.DefaultURL)
187 defer nc.Close()
188
189 nc.Subscribe("foo", func(m *nats.Msg) {
190 nc.Publish(m.Reply, []byte("I will help you"))
191 })
192 nc.Request("foo", []byte("help"), 50*time.Millisecond)
193 }
194
195 func ExampleConn_QueueSubscribe() {
196 nc, _ := nats.Connect(nats.DefaultURL)
197 defer nc.Close()
198
199 received := 0
200
201 nc.QueueSubscribe("foo", "worker_group", func(_ *nats.Msg) {
202 received++
203 })
204 }
205
206 func ExampleSubscription_AutoUnsubscribe() {
207 nc, _ := nats.Connect(nats.DefaultURL)
208 defer nc.Close()
209
210 received, wanted, total := 0, 10, 100
211
212 sub, _ := nc.Subscribe("foo", func(_ *nats.Msg) {
213 received++
214 })
215 sub.AutoUnsubscribe(wanted)
216
217 for i := 0; i < total; i++ {
218 nc.Publish("foo", []byte("Hello"))
219 }
220 nc.Flush()
221
222 fmt.Printf("Received = %d", received)
223 }
224
225 func ExampleConn_Close() {
226 nc, _ := nats.Connect(nats.DefaultURL)
227 nc.Close()
228 }
229
230 func ExampleJetStream() {
231 nc, err := nats.Connect("localhost")
232 if err != nil {
233 log.Fatal(err)
234 }
235
236 // Use the JetStream context to produce and consumer messages
237 // that have been persisted.
238 js, err := nc.JetStream(nats.PublishAsyncMaxPending(256))
239 if err != nil {
240 log.Fatal(err)
241 }
242
243 js.AddStream(&nats.StreamConfig{
244 Name: "FOO",
245 Subjects: []string{"foo"},
246 })
247
248 js.Publish("foo", []byte("Hello JS!"))
249
250 // Publish messages asynchronously.
251 for i := 0; i < 500; i++ {
252 js.PublishAsync("foo", []byte("Hello JS Async!"))
253 }
254 select {
255 case <-js.PublishAsyncComplete():
256 case <-time.After(5 * time.Second):
257 fmt.Println("Did not resolve in time")
258 }
259
260 // Create async consumer on subject 'foo'. Async subscribers
261 // ack a message once exiting the callback.
262 js.Subscribe("foo", func(msg *nats.Msg) {
263 meta, _ := msg.Metadata()
264 fmt.Printf("Stream Sequence : %v\n", meta.Sequence.Stream)
265 fmt.Printf("Consumer Sequence: %v\n", meta.Sequence.Consumer)
266 })
267
268 // Async subscriber with manual acks.
269 js.Subscribe("foo", func(msg *nats.Msg) {
270 msg.Ack()
271 }, nats.ManualAck())
272
273 // Async queue subscription where members load balance the
274 // received messages together.
275 // If no consumer name is specified, either with nats.Bind()
276 // or nats.Durable() options, the queue name is used as the
277 // durable name (that is, as if you were passing the
278 // nats.Durable(<queue group name>) option.
279 // It is recommended to use nats.Bind() or nats.Durable()
280 // and preferably create the JetStream consumer beforehand
281 // (using js.AddConsumer) so that the JS consumer is not
282 // deleted on an Unsubscribe() or Drain() when the member
283 // that created the consumer goes away first.
284 // Check Godoc for the QueueSubscribe() API for more details.
285 js.QueueSubscribe("foo", "group", func(msg *nats.Msg) {
286 msg.Ack()
287 }, nats.ManualAck())
288
289 // Subscriber to consume messages synchronously.
290 sub, _ := js.SubscribeSync("foo")
291 msg, _ := sub.NextMsg(2 * time.Second)
292 msg.Ack()
293
294 // We can add a member to the group, with this member using
295 // the synchronous version of the QueueSubscribe.
296 sub, _ = js.QueueSubscribeSync("foo", "group")
297 msg, _ = sub.NextMsg(2 * time.Second)
298 msg.Ack()
299
300 // ChanSubscribe
301 msgCh := make(chan *nats.Msg, 8192)
302 sub, _ = js.ChanSubscribe("foo", msgCh)
303
304 select {
305 case msg := <-msgCh:
306 fmt.Println("[Received]", msg)
307 case <-time.After(1 * time.Second):
308 }
309
310 // Create Pull based consumer with maximum 128 inflight.
311 sub, _ = js.PullSubscribe("foo", "wq", nats.PullMaxWaiting(128))
312
313 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
314 defer cancel()
315
316 for {
317 select {
318 case <-ctx.Done():
319 return
320 default:
321 }
322
323 msgs, _ := sub.Fetch(10, nats.Context(ctx))
324 for _, msg := range msgs {
325 msg.Ack()
326 }
327 }
328 }
329
330 // A JetStream context can be configured with a default timeout using nats.MaxWait
331 // or with a custom API prefix in case of using an imported JetStream from another account.
332 func ExampleJSOpt() {
333 nc, err := nats.Connect("localhost")
334 if err != nil {
335 log.Fatal(err)
336 }
337
338 // Use the JetStream context to manage streams and consumers (with nats.APIPrefix JSOpt)
339 js, err := nc.JetStream(nats.APIPrefix("dlc"), nats.MaxWait(5*time.Second))
340 if err != nil {
341 log.Fatal(err)
342 }
343 sub, _ := js.SubscribeSync("foo")
344 js.Publish("foo", []byte("Hello JS!"))
345 sub.NextMsg(2 * time.Second)
346 }
347
348 func ExampleJetStreamManager() {
349 nc, _ := nats.Connect("localhost")
350
351 js, _ := nc.JetStream()
352
353 // Create a stream
354 js.AddStream(&nats.StreamConfig{
355 Name: "FOO",
356 Subjects: []string{"foo"},
357 MaxBytes: 1024,
358 })
359
360 // Update a stream
361 js.UpdateStream(&nats.StreamConfig{
362 Name: "FOO",
363 MaxBytes: 2048,
364 })
365
366 // Create a durable consumer
367 js.AddConsumer("FOO", &nats.ConsumerConfig{
368 Durable: "BAR",
369 })
370
371 // Get information about all streams (with Context JSOpt)
372 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
373 defer cancel()
374 for info := range js.StreamsInfo(nats.Context(ctx)) {
375 fmt.Println("stream name:", info.Config.Name)
376 }
377
378 // Get information about all consumers (with MaxWait JSOpt)
379 for info := range js.ConsumersInfo("FOO", nats.MaxWait(10*time.Second)) {
380 fmt.Println("consumer name:", info.Name)
381 }
382
383 // Delete a consumer
384 js.DeleteConsumer("FOO", "BAR")
385
386 // Delete a stream
387 js.DeleteStream("FOO")
388 }
389
390 // A JetStreamContext is the composition of a JetStream and JetStreamManagement interfaces.
391 // In case of only requiring publishing/consuming messages, can create a context that
392 // only uses the JetStream interface.
393 func ExampleJetStreamContext() {
394 nc, _ := nats.Connect("localhost")
395
396 var js nats.JetStream
397 var jsm nats.JetStreamManager
398 var jsctx nats.JetStreamContext
399
400 // JetStream that can publish/subscribe but cannot manage streams.
401 js, _ = nc.JetStream()
402 js.Publish("foo", []byte("hello"))
403
404 // JetStream context that can manage streams/consumers but cannot produce messages.
405 jsm, _ = nc.JetStream()
406 jsm.AddStream(&nats.StreamConfig{Name: "FOO"})
407
408 // JetStream context that can both manage streams/consumers
409 // as well as publish/subscribe.
410 jsctx, _ = nc.JetStream()
411 jsctx.AddStream(&nats.StreamConfig{Name: "BAR"})
412 jsctx.Publish("bar", []byte("hello world"))
413 }
414
415 func ExamplePubOpt() {
416 nc, err := nats.Connect("localhost")
417 if err != nil {
418 log.Fatal(err)
419 }
420
421 // Create JetStream context to produce/consumer messages that will be persisted.
422 js, err := nc.JetStream()
423 if err != nil {
424 log.Fatal(err)
425 }
426
427 // Create stream to persist messages published on 'foo'.
428 js.AddStream(&nats.StreamConfig{
429 Name: "FOO",
430 Subjects: []string{"foo"},
431 })
432
433 // Publish is synchronous by default, and waits for a PubAck response.
434 js.Publish("foo", []byte("Hello JS!"))
435
436 // Publish with a custom timeout.
437 js.Publish("foo", []byte("Hello JS!"), nats.AckWait(500*time.Millisecond))
438
439 // Publish with a context.
440 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
441 defer cancel()
442
443 js.Publish("foo", []byte("Hello JS!"), nats.Context(ctx))
444
445 // Publish and assert the expected stream name.
446 js.Publish("foo", []byte("Hello JS!"), nats.ExpectStream("FOO"))
447
448 // Publish and assert the last sequence.
449 js.Publish("foo", []byte("Hello JS!"), nats.ExpectLastSequence(5))
450
451 // Publish and tag the message with an ID.
452 js.Publish("foo", []byte("Hello JS!"), nats.MsgId("foo:6"))
453
454 // Publish and assert the last msg ID.
455 js.Publish("foo", []byte("Hello JS!"), nats.ExpectLastMsgId("foo:6"))
456 }
457
458 func ExampleSubOpt() {
459 nc, err := nats.Connect("localhost")
460 if err != nil {
461 log.Fatal(err)
462 }
463
464 // Create JetStream context to produce/consumer messages that will be persisted.
465 js, err := nc.JetStream()
466 if err != nil {
467 log.Fatal(err)
468 }
469
470 // Auto-ack each individual message.
471 js.Subscribe("foo", func(msg *nats.Msg) {
472 fmt.Printf("Received a message: %s\n", string(msg.Data))
473 })
474
475 // Auto-ack current sequence and all below.
476 js.Subscribe("foo", func(msg *nats.Msg) {
477 fmt.Printf("Received a message: %s\n", string(msg.Data))
478 }, nats.AckAll())
479
480 // Auto-ack each individual message.
481 js.Subscribe("foo", func(msg *nats.Msg) {
482 fmt.Printf("Received a message: %s\n", string(msg.Data))
483 }, nats.AckExplicit())
484
485 // Acks are not required.
486 js.Subscribe("foo", func(msg *nats.Msg) {
487 fmt.Printf("Received a message: %s\n", string(msg.Data))
488 }, nats.AckNone())
489
490 // Manually acknowledge messages.
491 js.Subscribe("foo", func(msg *nats.Msg) {
492 msg.Ack()
493 }, nats.ManualAck())
494
495 // Bind to an existing stream.
496 sub, _ := js.SubscribeSync("origin", nats.BindStream("m1"))
497 msg, _ := sub.NextMsg(2 * time.Second)
498 msg.Ack()
499
500 // Deliver all messages from the beginning.
501 js.Subscribe("foo", func(msg *nats.Msg) {
502 fmt.Printf("Received a message: %s\n", string(msg.Data))
503 }, nats.DeliverAll())
504
505 // Deliver messages starting from the last one.
506 js.Subscribe("foo", func(msg *nats.Msg) {
507 fmt.Printf("Received a message: %s\n", string(msg.Data))
508 }, nats.DeliverLast())
509
510 // Deliver only new messages that arrive after subscription.
511 js.Subscribe("foo", func(msg *nats.Msg) {
512 fmt.Printf("Received a message: %s\n", string(msg.Data))
513 }, nats.DeliverNew())
514
515 // Create durable consumer FOO, if it doesn't exist.
516 js.Subscribe("foo", func(msg *nats.Msg) {
517 fmt.Printf("Received a message: %s\n", string(msg.Data))
518 }, nats.Durable("FOO"))
519
520 // Create consumer on Foo with flow control and heartbeats.
521 js.SubscribeSync("foo",
522 // Redeliver after 30s
523 nats.AckWait(30*time.Second),
524 // Redeliver only once
525 nats.MaxDeliver(1),
526 // Activate Flow control algorithm from the server.
527 nats.EnableFlowControl(),
528 // Track heartbeats from the server for missed sequences.
529 nats.IdleHeartbeat(500*time.Millisecond),
530 )
531
532 // Set the allowable number of outstanding acks.
533 js.Subscribe("foo", func(msg *nats.Msg) {
534 fmt.Printf("Received a message: %s\n", string(msg.Data))
535 }, nats.MaxAckPending(5))
536
537 // Set the number of redeliveries for a message.
538 js.Subscribe("foo", func(msg *nats.Msg) {
539 fmt.Printf("Received a message: %s\n", string(msg.Data))
540 }, nats.MaxDeliver(5))
541
542 // Set the number the max inflight pull requests.
543 js.Subscribe("foo", func(msg *nats.Msg) {
544 fmt.Printf("Received a message: %s\n", string(msg.Data))
545 }, nats.PullMaxWaiting(5))
546
547 // Set the number the max inflight pull requests.
548 js.Subscribe("foo", func(msg *nats.Msg) {
549 fmt.Printf("Received a message: %s\n", string(msg.Data))
550 }, nats.PullMaxWaiting(5))
551
552 // Set the rate limit on a push consumer.
553 js.Subscribe("foo", func(msg *nats.Msg) {
554 fmt.Printf("Received a message: %s\n", string(msg.Data))
555 }, nats.RateLimit(1024))
556
557 // Replay messages at original speed, instead of as fast as possible.
558 js.Subscribe("foo", func(msg *nats.Msg) {
559 fmt.Printf("Received a message: %s\n", string(msg.Data))
560 }, nats.ReplayOriginal())
561
562 // Start delivering messages at a given sequence.
563 js.Subscribe("foo", func(msg *nats.Msg) {
564 fmt.Printf("Received a message: %s\n", string(msg.Data))
565 }, nats.StartSequence(10))
566
567 // Start delivering messages at a given time.
568 js.Subscribe("foo", func(msg *nats.Msg) {
569 fmt.Printf("Received a message: %s\n", string(msg.Data))
570 }, nats.StartTime(time.Now().Add(-2*time.Hour)))
571
572 // Start delivering messages with delay based on BackOff array of time durations.
573 js.Subscribe("foo", func(msg *nats.Msg) {
574 fmt.Printf("Received a message: %s\n", string(msg.Data))
575 }, nats.ManualAck(), nats.MaxDeliver(2), nats.BackOff([]time.Duration{50 * time.Millisecond, 250 * time.Millisecond}))
576
577 // Set consumer replicas count for a durable while subscribing.
578 js.Subscribe("foo", func(msg *nats.Msg) {
579 fmt.Printf("Received a message: %s\n", string(msg.Data))
580 }, nats.Durable("FOO"), nats.ConsumerReplicas(1))
581
582 // Force memory storage while subscribing.
583 js.Subscribe("foo", func(msg *nats.Msg) {
584 fmt.Printf("Received a message: %s\n", string(msg.Data))
585 }, nats.Durable("FOO"), nats.ConsumerMemoryStorage())
586
587 // Skip consumer lookup when using explicit consumer name
588 js.Subscribe("foo", func(msg *nats.Msg) {
589 fmt.Printf("Received a message: %s\n", string(msg.Data))
590 }, nats.Durable("FOO"), nats.SkipConsumerLookup())
591
592 // Use multiple subject filters.
593 js.Subscribe("", func(msg *nats.Msg) {
594 fmt.Printf("Received a message: %s\n", string(msg.Data))
595 }, nats.Durable("FOO"), nats.ConsumerFilterSubjects("foo", "bar"), nats.BindStream("test_stream"))
596 }
597
598 func ExampleMaxWait() {
599 nc, _ := nats.Connect("localhost")
600
601 // Set default timeout for JetStream API requests,
602 // following requests will inherit this timeout.
603 js, _ := nc.JetStream(nats.MaxWait(3 * time.Second))
604
605 // Set custom timeout for a JetStream API request.
606 js.AddStream(&nats.StreamConfig{
607 Name: "FOO",
608 Subjects: []string{"foo"},
609 }, nats.MaxWait(2*time.Second))
610
611 sub, _ := js.PullSubscribe("foo", "my-durable-name")
612
613 // Fetch using the default timeout of 3 seconds.
614 msgs, _ := sub.Fetch(1)
615
616 // Set custom timeout for a pull batch request.
617 msgs, _ = sub.Fetch(1, nats.MaxWait(2*time.Second))
618
619 for _, msg := range msgs {
620 msg.Ack()
621 }
622 }
623
624 func ExampleAckWait() {
625 nc, _ := nats.Connect("localhost")
626 js, _ := nc.JetStream()
627
628 // Set custom timeout for a JetStream API request.
629 js.AddStream(&nats.StreamConfig{
630 Name: "FOO",
631 Subjects: []string{"foo"},
632 })
633
634 // Wait for an ack response for 2 seconds.
635 js.Publish("foo", []byte("Hello JS!"), nats.AckWait(2*time.Second))
636
637 // Create consumer on 'foo' subject that waits for an ack for 10s,
638 // after which the message will be delivered.
639 sub, _ := js.SubscribeSync("foo", nats.AckWait(10*time.Second))
640 msg, _ := sub.NextMsg(2 * time.Second)
641
642 // Wait for ack of ack for 2s.
643 msg.AckSync(nats.AckWait(2 * time.Second))
644 }
645
646 func ExampleMsg_AckSync() {
647 nc, _ := nats.Connect("localhost")
648 js, _ := nc.JetStream()
649
650 // Set custom timeout for a JetStream API request.
651 js.AddStream(&nats.StreamConfig{
652 Name: "FOO",
653 Subjects: []string{"foo"},
654 })
655
656 sub, _ := js.SubscribeSync("foo")
657 msg, _ := sub.NextMsg(2 * time.Second)
658
659 // Wait for ack of an ack.
660 msg.AckSync()
661 }
662
663 // When a message has been delivered by JetStream, it will be possible
664 // to access some of its metadata such as sequence numbers.
665 func ExampleMsg_Metadata() {
666 nc, _ := nats.Connect("localhost")
667 js, _ := nc.JetStream()
668
669 // Set custom timeout for a JetStream API request.
670 js.AddStream(&nats.StreamConfig{
671 Name: "FOO",
672 Subjects: []string{"foo"},
673 })
674
675 js.Publish("foo", []byte("hello"))
676
677 sub, _ := js.SubscribeSync("foo")
678 msg, _ := sub.NextMsg(2 * time.Second)
679
680 //
681 meta, _ := msg.Metadata()
682
683 // Stream and Consumer sequences.
684 fmt.Printf("Stream seq: %s:%d, Consumer seq: %s:%d\n", meta.Stream, meta.Sequence.Stream, meta.Consumer, meta.Sequence.Consumer)
685 fmt.Printf("Pending: %d\n", meta.NumPending)
686 fmt.Printf("Pending: %d\n", meta.NumDelivered)
687 }
688
689 // AckOpt are the options that can be passed when acknowledge a message.
690 func ExampleAckOpt() {
691 nc, err := nats.Connect("localhost")
692 if err != nil {
693 log.Fatal(err)
694 }
695
696 // Create JetStream context to produce/consumer messages that will be persisted.
697 js, err := nc.JetStream()
698 if err != nil {
699 log.Fatal(err)
700 }
701
702 // Create stream to persist messages published on 'foo'.
703 js.AddStream(&nats.StreamConfig{
704 Name: "FOO",
705 Subjects: []string{"foo"},
706 })
707
708 // Publish is synchronous by default, and waits for a PubAck response.
709 js.Publish("foo", []byte("Hello JS!"))
710
711 sub, _ := js.SubscribeSync("foo")
712 msg, _ := sub.NextMsg(2 * time.Second)
713
714 // Ack and wait for 2 seconds
715 msg.InProgress(nats.AckWait(2))
716
717 // Using a context.
718 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
719 defer cancel()
720 msg.Ack(nats.Context(ctx))
721 }
722
723 func ExamplePullOpt() {
724 nc, err := nats.Connect("localhost")
725 if err != nil {
726 log.Fatal(err)
727 }
728
729 // Create JetStream context to produce/consumer messages that will be persisted.
730 js, err := nc.JetStream()
731 if err != nil {
732 log.Fatal(err)
733 }
734
735 // Create stream to persist messages published on 'foo'.
736 js.AddStream(&nats.StreamConfig{
737 Name: "FOO",
738 Subjects: []string{"foo"},
739 })
740
741 // Publish is synchronous by default, and waits for a PubAck response.
742 js.Publish("foo", []byte("Hello JS!"))
743
744 sub, _ := js.PullSubscribe("foo", "wq")
745
746 // Pull one message,
747 msgs, _ := sub.Fetch(1, nats.MaxWait(2*time.Second))
748 for _, msg := range msgs {
749 msg.Ack()
750 }
751
752 // Using a context to timeout waiting for a message.
753 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
754 defer cancel()
755
756 msgs, _ = sub.Fetch(1, nats.Context(ctx))
757 for _, msg := range msgs {
758 msg.Ack()
759 }
760 }
761
762 func ExampleContext() {
763 nc, err := nats.Connect("localhost")
764 if err != nil {
765 log.Fatal(err)
766 }
767
768 js, _ := nc.JetStream()
769
770 // Base context
771 ctx, cancel := context.WithCancel(context.Background())
772 defer cancel()
773
774 // nats.Context option implements context.Context interface, so can be used
775 // to create a new context from top level one.
776 nctx := nats.Context(ctx)
777
778 // JetStreamManager functions all can use context.
779 js.AddStream(&nats.StreamConfig{
780 Name: "FOO",
781 Subjects: []string{"foo"},
782 }, nctx)
783
784 // Custom context with timeout
785 tctx, tcancel := context.WithTimeout(nctx, 2*time.Second)
786 defer tcancel()
787
788 // Set a timeout for publishing using context.
789 deadlineCtx := nats.Context(tctx)
790
791 js.Publish("foo", []byte("Hello JS!"), deadlineCtx)
792 sub, _ := js.SubscribeSync("foo")
793 msg, _ := sub.NextMsgWithContext(deadlineCtx)
794
795 // Acks can also use a context to await for a response.
796 msg.Ack(deadlineCtx)
797 }