| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"fmt" |
| 6 |
"time" |
| 7 |
|
| 8 |
"github.com/nats-io/nats.go" |
| 9 |
"github.com/nats-io/nats.go/jetstream" |
| 10 |
) |
| 11 |
|
| 12 |
func main() { |
| 13 |
// Connect to the NATS server. |
| 14 |
nc, err := nats.Connect("nats://localhost:4222") |
| 15 |
if err != nil { |
| 16 |
panic(err) |
| 17 |
} |
| 18 |
defer nc.Close() |
| 19 |
|
| 20 |
// Create a JetStream context (the stream manager). |
| 21 |
js, err := jetstream.New(nc) |
| 22 |
if err != nil { |
| 23 |
panic(err) |
| 24 |
} |
| 25 |
|
| 26 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 27 |
defer cancel() |
| 28 |
|
| 29 |
// NATS-DOC-START |
| 30 |
// Create a durable pull consumer named "analytics" on the ORDERS stream. |
| 31 |
// FilterSubject narrows delivery to "orders.shipped", so the consumer never |
| 32 |
// sees "orders.created" messages even though the stream stores both. |
| 33 |
cons, err := js.CreateOrUpdateConsumer(ctx, "ORDERS", jetstream.ConsumerConfig{ |
| 34 |
Durable: "analytics", |
| 35 |
FilterSubject: "orders.shipped", |
| 36 |
DeliverPolicy: jetstream.DeliverAllPolicy, |
| 37 |
AckPolicy: jetstream.AckExplicitPolicy, |
| 38 |
}) |
| 39 |
if err != nil { |
| 40 |
panic(err) |
| 41 |
} |
| 42 |
|
| 43 |
fmt.Printf("Created consumer: %s\n", cons.CachedInfo().Name) |
| 44 |
fmt.Printf("Filter: %s\n", cons.CachedInfo().Config.FilterSubject) |
| 45 |
|
| 46 |
// Fetch up to 5 messages with a short expiry. Only "orders.shipped" |
| 47 |
// messages come back; the filter excludes everything else. |
| 48 |
msgs, err := cons.Fetch(5, jetstream.FetchMaxWait(2*time.Second)) |
| 49 |
if err != nil { |
| 50 |
panic(err) |
| 51 |
} |
| 52 |
for msg := range msgs.Messages() { |
| 53 |
fmt.Printf("Received on %s\n", msg.Subject()) |
| 54 |
msg.Ack() |
| 55 |
} |
| 56 |
if err := msgs.Error(); err != nil { |
| 57 |
panic(err) |
| 58 |
} |
| 59 |
// NATS-DOC-END |
| 60 |
} |