| 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 |
// Publish three order messages into the ORDERS stream. Each Publish blocks |
| 31 |
// until the server replies with a PubAck confirming where it was stored. |
| 32 |
orders := []struct { |
| 33 |
subject string |
| 34 |
payload string |
| 35 |
}{ |
| 36 |
{"orders.created", `{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}`}, |
| 37 |
{"orders.created", `{"order_id":"ord_2zr9","customer":"globex","total_cents":7800,"ts":"2026-05-22T10:14:25Z"}`}, |
| 38 |
{"orders.shipped", `{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:31Z"}`}, |
| 39 |
} |
| 40 |
|
| 41 |
for _, order := range orders { |
| 42 |
ack, err := js.Publish(ctx, order.subject, []byte(order.payload)) |
| 43 |
if err != nil { |
| 44 |
panic(err) |
| 45 |
} |
| 46 |
fmt.Printf("Stored in %s, sequence %d\n", ack.Stream, ack.Sequence) |
| 47 |
} |
| 48 |
// NATS-DOC-END |
| 49 |
} |