| 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 |
// Per-message TTL only works when the stream opts in with AllowMsgTTL. |
| 30 |
_, err = js.CreateStream(ctx, jetstream.StreamConfig{ |
| 31 |
Name: "ORDERS", |
| 32 |
Subjects: []string{"orders.>"}, |
| 33 |
AllowMsgTTL: true, |
| 34 |
}) |
| 35 |
if err != nil { |
| 36 |
panic(err) |
| 37 |
} |
| 38 |
|
| 39 |
// NATS-DOC-START |
| 40 |
// Publish with a 60-second TTL. WithMsgTTL sets the Nats-TTL header, so the |
| 41 |
// server deletes this single message 60s after it is stored, ahead of the |
| 42 |
// stream's MaxAge. |
| 43 |
ack, err := js.Publish(ctx, "orders.canceled", []byte("order 42 canceled"), |
| 44 |
jetstream.WithMsgTTL(60*time.Second)) |
| 45 |
if err != nil { |
| 46 |
panic(err) |
| 47 |
} |
| 48 |
|
| 49 |
fmt.Printf("Stored in %s at sequence %d\n", ack.Stream, ack.Sequence) |
| 50 |
// NATS-DOC-END |
| 51 |
} |