MCPcopy
hub / github.com/nats-io/nats.go / ExampleSubOpt

Function ExampleSubOpt

example_test.go:458–596  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

456}
457
458func 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.

Callers

nothing calls this directly

Calls 7

ConnectMethod · 0.80
JetStreamMethod · 0.80
NextMsgMethod · 0.80
SubscribeMethod · 0.65
AckMethod · 0.65
SubscribeSyncMethod · 0.65
AddMethod · 0.65

Tested by

no test coverage detected