Debian Codegraph @

examples/docs/learn-jetstream-subject-mapping-transform/main.go

raw
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 // Create a stream that rewrites subjects as it stores them. The transform
31 // shards each customer into one of three buckets: partition(3,1) hashes the
32 // first wildcard token into 0, 1, or 2, and wildcard(1) keeps that token.
33 // So "ingest.alice" might land on "orders.2.alice".
34 stream, err := js.CreateStream(ctx, jetstream.StreamConfig{
35 Name: "ORDERS-SHARDED",
36 Subjects: []string{"ingest.*"},
37 SubjectTransform: &jetstream.SubjectTransformConfig{
38 Source: "ingest.*",
39 Destination: "orders.{{partition(3,1)}}.{{wildcard(1)}}",
40 },
41 })
42 if err != nil {
43 panic(err)
44 }
45
46 fmt.Printf("Created stream: %s\n", stream.CachedInfo().Config.Name)
47 // NATS-DOC-END
48 }