Debian Codegraph @

examples/jetstream/js-ordered-consume/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 "os"
21 "os/signal"
22 "syscall"
23 "time"
24
25 "github.com/nats-io/nats.go"
26 "github.com/nats-io/nats.go/jetstream"
27 )
28
29 func main() {
30 ctx, cancel := context.WithTimeout(context.Background(), 60*time.Minute)
31 defer cancel()
32
33 nc, err := nats.Connect("nats://127.0.0.1:4222")
34 if err != nil {
35 log.Fatal(err)
36 }
37
38 js, err := jetstream.New(nc)
39 if err != nil {
40 log.Fatal(err)
41 }
42 s, err := js.CreateStream(ctx, jetstream.StreamConfig{
43 Name: "TEST_STREAM",
44 Subjects: []string{"FOO.*"},
45 })
46 if err != nil {
47 log.Fatal(err)
48 }
49
50 cons, err := s.OrderedConsumer(ctx, jetstream.OrderedConsumerConfig{
51 MaxResetAttempts: 5,
52 })
53 if err != nil {
54 log.Fatal(err)
55 }
56 go endlessPublish(ctx, nc, js)
57
58 _, err = cons.Consume(func(msg jetstream.Msg) {
59 fmt.Println(string(msg.Data()))
60 msg.Ack()
61 })
62 if err != nil {
63 log.Fatal(err)
64 }
65 sig := make(chan os.Signal, 1)
66 signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
67 <-sig
68
69 }
70
71 func endlessPublish(ctx context.Context, nc *nats.Conn, js jetstream.JetStream) {
72 var i int
73 for {
74 time.Sleep(500 * time.Millisecond)
75 if nc.Status() != nats.CONNECTED {
76 continue
77 }
78 if _, err := js.Publish(ctx, "FOO.TEST1", []byte(fmt.Sprintf("msg %d", i))); err != nil {
79 fmt.Println("pub error: ", err)
80 }
81 i++
82 }
83 }