-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsubscriber_example_test.go
41 lines (34 loc) · 1020 Bytes
/
subscriber_example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package spream_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/signal"
"sync"
"cloud.google.com/go/spanner"
"github.com/toga4/spream"
"github.com/toga4/spream/partitionstorage"
)
func ExampleNewSubscriber() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
defer stop()
database := fmt.Sprintf("projects/%s/instances/%s/databases/%s", "foo-project", "foo-instance", "foo-database")
spannerClient, err := spanner.NewClient(ctx, database)
if err != nil {
panic(err)
}
defer spannerClient.Close()
changeStreamName := "FooStream"
subscriber := spream.NewSubscriber(spannerClient, changeStreamName, partitionstorage.NewInmemory())
fmt.Fprintf(os.Stderr, "Reading the stream...\n")
var mu sync.Mutex
if err := subscriber.SubscribeFunc(ctx, func(change *spream.DataChangeRecord) error {
mu.Lock()
defer mu.Unlock()
return json.NewEncoder(os.Stdout).Encode(change)
}); err != nil && !errors.Is(ctx.Err(), context.Canceled) {
panic(err)
}
}