| 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 |
// This stream never opted in: AllowMsgTTL is left at its default (false). |
| 30 |
_, err = js.CreateStream(ctx, jetstream.StreamConfig{ |
| 31 |
Name: "ORDERS_NO_TTL", |
| 32 |
Subjects: []string{"no-ttl.>"}, |
| 33 |
}) |
| 34 |
if err != nil { |
| 35 |
panic(err) |
| 36 |
} |
| 37 |
|
| 38 |
// NATS-DOC-START |
| 39 |
// Publishing with a TTL to a stream that hasn't enabled AllowMsgTTL fails. |
| 40 |
// The server returns "per-message TTL is disabled" (err_code 10166) and |
| 41 |
// stores nothing. The fix is to opt the stream in with AllowMsgTTL: true. |
| 42 |
_, err = js.Publish(ctx, "no-ttl.msg", []byte("order 42 canceled"), |
| 43 |
jetstream.WithMsgTTL(60*time.Second)) |
| 44 |
if err != nil { |
| 45 |
fmt.Printf("Publish rejected, message not stored: %s\n", err) |
| 46 |
return |
| 47 |
} |
| 48 |
// NATS-DOC-END |
| 49 |
} |