Created
May 19, 2021 19:36
-
-
Save wallyqs/7abb2c2598bbdae7772f7bbe2cb5fbcd to your computer and use it in GitHub Desktop.
Subscribing with Filter Subject and JS context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"github.com/nats-io/nats.go" | |
) | |
func main() { | |
nc, err := nats.Connect("localhost") | |
if err != nil { | |
log.Fatal(err) | |
} | |
js, err := nc.JetStream() | |
if err != nil { | |
log.Fatal(err) | |
} | |
js.AddStream(&nats.StreamConfig{ | |
Name: "foo", | |
Subjects: []string{"foo.*"}, | |
}) | |
// Create durable pull subscriber (no delivery subject) | |
_, err = js.AddConsumer("foo", &nats.ConsumerConfig{ | |
Durable: "d-foo", | |
FilterSubject: "foo.1", | |
AckPolicy: nats.AckExplicitPolicy, | |
}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Send message that matches stream wildcard. | |
js.Publish("foo.1", []byte("On foo.1")) | |
// Receive all messages. | |
js.Subscribe("foo.*", func(msg *nats.Msg) { | |
fmt.Println("[Recvd on foo.*]", msg) | |
}) | |
sub, err := js.PullSubscribe("foo.1", "d-foo", nats.BindStream("foo")) | |
if err != nil { | |
log.Fatal(err) | |
} | |
msgs, err := sub.Fetch(1) | |
if err != nil { | |
log.Fatal(err) | |
} | |
msg := msgs[0] | |
fmt.Println("[Recvd on foo.1]", string(msg.Data)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment