| 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.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{ |
| 51 |
Durable: "TestConsumerParallelConsume", |
| 52 |
AckPolicy: jetstream.AckExplicitPolicy, |
| 53 |
}) |
| 54 |
if err != nil { |
| 55 |
log.Fatal(err) |
| 56 |
} |
| 57 |
go endlessPublish(ctx, nc, js) |
| 58 |
|
| 59 |
for i := 0; i < 5; i++ { |
| 60 |
cc, err := cons.Consume(func(consumeID int) jetstream.MessageHandler { |
| 61 |
return func(msg jetstream.Msg) { |
| 62 |
fmt.Printf("Received msg on consume %d\n", consumeID) |
| 63 |
msg.Ack() |
| 64 |
} |
| 65 |
}(i), jetstream.ConsumeErrHandler(func(consumeCtx jetstream.ConsumeContext, err error) { |
| 66 |
fmt.Println(err) |
| 67 |
})) |
| 68 |
if err != nil { |
| 69 |
log.Fatal(err) |
| 70 |
} |
| 71 |
defer cc.Stop() |
| 72 |
} |
| 73 |
|
| 74 |
sig := make(chan os.Signal, 1) |
| 75 |
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) |
| 76 |
<-sig |
| 77 |
|
| 78 |
} |
| 79 |
|
| 80 |
func endlessPublish(ctx context.Context, nc *nats.Conn, js jetstream.JetStream) { |
| 81 |
var i int |
| 82 |
for { |
| 83 |
time.Sleep(500 * time.Millisecond) |
| 84 |
if nc.Status() != nats.CONNECTED { |
| 85 |
continue |
| 86 |
} |
| 87 |
if _, err := js.Publish(ctx, "FOO.TEST1", []byte(fmt.Sprintf("msg %d", i))); err != nil { |
| 88 |
fmt.Println("pub error: ", err) |
| 89 |
} |
| 90 |
i++ |
| 91 |
} |
| 92 |
} |