| 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. |
| 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 "shipping" consumer. |
| 31 |
cons, err := js.Consumer(ctx, "ORDERS", "shipping") |
| 32 |
if err != nil { |
| 33 |
panic(err) |
| 34 |
} |
| 35 |
|
| 36 |
// Fetch a batch of up to 10 orders, waiting up to 2 seconds for them. The |
| 37 |
// call returns when the batch is full or the wait elapses, whichever comes |
| 38 |
// first. Process and ack each one, then fetch again to keep going. |
| 39 |
msgs, err := cons.Fetch(10, jetstream.FetchMaxWait(2*time.Second)) |
| 40 |
if err != nil { |
| 41 |
panic(err) |
| 42 |
} |
| 43 |
for msg := range msgs.Messages() { |
| 44 |
fmt.Printf("shipping %s\n", string(msg.Data())) |
| 45 |
msg.Ack() |
| 46 |
} |
| 47 |
if msgs.Error() != nil { |
| 48 |
panic(msgs.Error()) |
| 49 |
} |
| 50 |
// NATS-DOC-END |
| 51 |
} |