| 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") |