| 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 |
// Switch ORDERS to Discard New. Discard New never drops messages already |
| 31 |
// stored, so capping it at one message leaves the existing orders in place |
| 32 |
// and puts the stream instantly over its limit. The next publish is |
| 33 |
// rejected rather than evicting an older order. |
| 34 |
s, err := js.Stream(ctx, "ORDERS") |
| 35 |
if err != nil { |
| 36 |
panic(err) |
| 37 |
} |
| 38 |
cfg := s.CachedInfo().Config |
| 39 |
cfg.Discard = jetstream.DiscardNew |
| 40 |
cfg.MaxMsgs = 1 |
| 41 |
if _, err := js.UpdateStream(ctx, cfg); err != nil { |
| 42 |
panic(err) |
| 43 |
} |
| 44 |
|
| 45 |
// This publish hits the full stream and fails with "maximum messages |
| 46 |
// exceeded" instead of succeeding silently. Handle it in the publisher. |
| 47 |
if _, err := js.Publish(ctx, "orders.created", []byte(`{"order_id":"ord_8w2k"}`)); err != nil { |
| 48 |
fmt.Printf("publish rejected: %v\n", err) |
| 49 |
} |
| 50 |
|
| 51 |
// Put ORDERS back: Discard Old, no message cap (age and byte limits stay). |
| 52 |
cfg.Discard = jetstream.DiscardOld |
| 53 |
cfg.MaxMsgs = -1 |
| 54 |
if _, err := js.UpdateStream(ctx, cfg); err != nil { |
| 55 |
panic(err) |
| 56 |
} |
| 57 |
// NATS-DOC-END |
| 58 |
} |