| 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 |
// FULFILLMENT is the queue of paid orders awaiting shipment. With WorkQueue |
| 31 |
// retention the server keeps each message only until a consumer acks it, |
| 32 |
// then deletes it from the stream. |
| 33 |
stream, err := js.CreateStream(ctx, jetstream.StreamConfig{ |
| 34 |
Name: "FULFILLMENT", |
| 35 |
Subjects: []string{"fulfill.>"}, |
| 36 |
Retention: jetstream.WorkQueuePolicy, |
| 37 |
}) |
| 38 |
if err != nil { |
| 39 |
panic(err) |
| 40 |
} |
| 41 |
fmt.Printf("FULFILLMENT retention: %s\n", stream.CachedInfo().Config.Retention) |
| 42 |
|
| 43 |
// Queue one order to ship. |
| 44 |
if _, err := js.Publish(ctx, "fulfill.us", []byte(`{"order_id":"ord_8w2k","customer":"acme-co"}`)); err != nil { |
| 45 |
panic(err) |
| 46 |
} |
| 47 |
|
| 48 |
// A shipping worker binds to a durable pull consumer with explicit ack. |
| 49 |
cons, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{ |
| 50 |
Durable: "shippers", |
| 51 |
AckPolicy: jetstream.AckExplicitPolicy, |
| 52 |
}) |
| 53 |
if err != nil { |
| 54 |
panic(err) |
| 55 |
} |
| 56 |
|
| 57 |
// Fetch the order and ack it once the worker has shipped it. |
| 58 |
msgs, err := cons.Fetch(1) |
| 59 |
if err != nil { |
| 60 |
panic(err) |
| 61 |
} |
| 62 |
for msg := range msgs.Messages() { |
| 63 |
fmt.Printf("shipping order: %s\n", string(msg.Data())) |
| 64 |
if err := msg.Ack(); err != nil { |
| 65 |
panic(err) |
| 66 |
} |
| 67 |
} |
| 68 |
if msgs.Error() != nil { |
| 69 |
panic(msgs.Error()) |
| 70 |
} |
| 71 |
|
| 72 |
// The ack removed the task from the queue, so the stream is now empty. A |
| 73 |
// Limits stream like ORDERS would still hold the message; a WorkQueue |
| 74 |
// stream drains to zero as workers finish. |
| 75 |
info, err := stream.Info(ctx) |
| 76 |
if err != nil { |
| 77 |
panic(err) |
| 78 |
} |
| 79 |
fmt.Printf("messages left in FULFILLMENT: %d\n", info.State.Msgs) |
| 80 |
// NATS-DOC-END |
| 81 |
} |