Debian Codegraph @

examples/jetstream/js-next/main.go

raw
1 // Copyright 2020-2022 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package main
15
16 import (
17 "context"
18 "fmt"
19 "log"
20 "time"
21
22 "github.com/nats-io/nats.go"
23 "github.com/nats-io/nats.go/jetstream"
24 )
25
26 func main() {
27 ctx, cancel := context.WithTimeout(context.Background(), 60*time.Minute)
28 defer cancel()
29
30 nc, err := nats.Connect("nats://127.0.0.1:4222")
31 if err != nil {
32 log.Fatal(err)
33 }
34
35 js, err := jetstream.New(nc)
36 if err != nil {
37 log.Fatal(err)
38 }
39 s, err := js.CreateStream(ctx, jetstream.StreamConfig{
40 Name: "TEST_STREAM",
41 Subjects: []string{"FOO.*"},
42 })
43 if err != nil {
44 log.Fatal(err)
45 }
46
47 cons, err := s.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
48 Durable: "TestConsumerListener",
49 AckPolicy: jetstream.AckExplicitPolicy,
50 })
51 if err != nil {
52 log.Fatal(err)
53 }
54 go endlessPublish(ctx, nc, js)
55
56 for {
57 msg, err := cons.Next()
58 if err != nil {
59 fmt.Println(err)
60 continue
61 }
62 fmt.Println(string(msg.Data()))
63 msg.Ack()
64 }
65 }
66
67 func endlessPublish(ctx context.Context, nc *nats.Conn, js jetstream.JetStream) {
68 var i int
69 for {
70 time.Sleep(500 * time.Millisecond)
71 if nc.Status() != nats.CONNECTED {
72 continue
73 }
74 if _, err := js.Publish(ctx, "FOO.TEST1", []byte(fmt.Sprintf("msg %d", i))); err != nil {
75 fmt.Println("pub error: ", err)
76 }
77 i++
78 }
79 }