snapshot of https://github.com/ThreeDotsLabs/watermill.git (master, 2026-09-15; blobs > 131072B omitted)
Some checks failed
master / ci (push) Failing after 0s
Some checks failed
master / ci (push) Failing after 0s
This commit is contained in:
82
_examples/pubsubs/nats-streaming/main.go
Normal file
82
_examples/pubsubs/nats-streaming/main.go
Normal file
@@ -0,0 +1,82 @@
|
||||
// Sources for https://watermill.io/learn/getting-started/
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
stan "github.com/nats-io/stan.go"
|
||||
|
||||
"github.com/ThreeDotsLabs/watermill"
|
||||
"github.com/ThreeDotsLabs/watermill-nats/pkg/nats"
|
||||
"github.com/ThreeDotsLabs/watermill/message"
|
||||
)
|
||||
|
||||
func main() {
|
||||
subscriber, err := nats.NewStreamingSubscriber(
|
||||
nats.StreamingSubscriberConfig{
|
||||
ClusterID: "test-cluster",
|
||||
ClientID: "example-subscriber",
|
||||
QueueGroup: "example",
|
||||
DurableName: "my-durable",
|
||||
SubscribersCount: 4, // how many goroutines should consume messages
|
||||
CloseTimeout: time.Minute,
|
||||
AckWaitTimeout: time.Second * 30,
|
||||
StanOptions: []stan.Option{
|
||||
stan.NatsURL("nats://nats-streaming:4222"),
|
||||
},
|
||||
Unmarshaler: nats.GobMarshaler{},
|
||||
},
|
||||
watermill.NewStdLogger(false, false),
|
||||
)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
messages, err := subscriber.Subscribe(context.Background(), "example.topic")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
go process(messages)
|
||||
|
||||
publisher, err := nats.NewStreamingPublisher(
|
||||
nats.StreamingPublisherConfig{
|
||||
ClusterID: "test-cluster",
|
||||
ClientID: "example-publisher",
|
||||
StanOptions: []stan.Option{
|
||||
stan.NatsURL("nats://nats-streaming:4222"),
|
||||
},
|
||||
Marshaler: nats.GobMarshaler{},
|
||||
},
|
||||
watermill.NewStdLogger(false, false),
|
||||
)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
publishMessages(publisher)
|
||||
}
|
||||
|
||||
func publishMessages(publisher message.Publisher) {
|
||||
for {
|
||||
msg := message.NewMessage(watermill.NewUUID(), []byte("Hello, world!"))
|
||||
|
||||
if err := publisher.Publish("example.topic", msg); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func process(messages <-chan *message.Message) {
|
||||
for msg := range messages {
|
||||
log.Printf("received message: %s, payload: %s", msg.UUID, string(msg.Payload))
|
||||
|
||||
// we need to Acknowledge that we received and processed the message,
|
||||
// otherwise, it will be resent over and over again.
|
||||
msg.Ack()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user