| 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 |
// Bind to the durable consumer created earlier. |
| 31 |
cons, err := js.Consumer(ctx, "ORDERS", "billing") |
| 32 |
if err != nil { |
| 33 |
panic(err) |
| 34 |
} |
| 35 |
|
| 36 |
// Ask the consumer how many messages are still waiting, then read exactly |
| 37 |
// that many. This drains everything stored without assuming a count. |
| 38 |
info, err := cons.Info(ctx) |
| 39 |
if err != nil { |
| 40 |
panic(err) |
| 41 |
} |
| 42 |
pending := info.NumPending |
| 43 |
if pending == 0 { |
| 44 |
fmt.Println("nothing to read") |
| 45 |
return |
| 46 |
} |
| 47 |
|
| 48 |
msgs, err := cons.Fetch(int(pending)) |
| 49 |
if err != nil { |
| 50 |
panic(err) |
| 51 |
} |
| 52 |
|
| 53 |
for msg := range msgs.Messages() { |
| 54 |
// Metadata carries the position of this message in the stream and in |
| 55 |
// the consumer's own delivery sequence. |
| 56 |
meta, err := msg.Metadata() |
| 57 |
if err != nil { |
| 58 |
panic(err) |
| 59 |
} |
| 60 |
fmt.Printf("stream seq=%d consumer seq=%d payload=%s\n", |
| 61 |
meta.Sequence.Stream, meta.Sequence.Consumer, string(msg.Data())) |
| 62 |
|
| 63 |
// Acknowledge so the server advances the consumer past this message. |
| 64 |
if err := msg.Ack(); err != nil { |
| 65 |
panic(err) |
| 66 |
} |
| 67 |
} |
| 68 |
if msgs.Error() != nil { |
| 69 |
panic(msgs.Error()) |
| 70 |
} |
| 71 |
// NATS-DOC-END |
| 72 |
} |