Debian Codegraph @

examples/jetstream/js-ordered-fetch/main.go

raw
1 // Copyright 2022-2023 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.OrderedConsumer(ctx, jetstream.OrderedConsumerConfig{
48 MaxResetAttempts: 5,
49 })
50 if err != nil {
51 log.Fatal(err)
52 }
53 go endlessPublish(ctx, nc, js)
54
55 for {
56 msgs, err := cons.Fetch(100)
57 if err != nil {
58 fmt.Println(err)
59 }
60 for msg := range msgs.Messages() {
61 fmt.Println(string(msg.Data()))
62 msg.Ack()
63 }
64 if msgs.Error() != nil {
65 fmt.Println("Error fetching messages: ", err)
66 }
67 }
68 }
69
70 func endlessPublish(ctx context.Context, nc *nats.Conn, js jetstream.JetStream) {
71 var i int
72 for {
73 time.Sleep(500 * time.Millisecond)
74 if nc.Status() != nats.CONNECTED {
75 continue
76 }
77 if _, err := js.Publish(ctx, "FOO.TEST1", []byte(fmt.Sprintf("msg %d", i))); err != nil {
78 fmt.Println("pub error: ", err)
79 }
80 i++
81 }
82 }